C fcntl () не работает?Проверка, заблокирован ли файл или нет - PullRequest
0 голосов
/ 24 июня 2018

Таким образом, эта программа создает один файл с именем testlock и устанавливает F_RDLCK и F_WRLCK для некоторых областей файла.Код ниже:

#include <string.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <fcntl.h>

int main() {
        const char *tfile = "testlock";
        char *byte_to_write = "Z";
        struct flock reg1;
        struct flock reg2;
        int byte_count;
        int res;

        int fd = open(tfile, O_RDWR | O_CREAT , 0666);
        if(fd) {
                for(byte_count = 0; byte_count < 100; byte_count++) {
                        (void)write(fd, byte_to_write, 1);
                }
        }

        reg1.l_type = F_RDLCK;
        reg1.l_whence = SEEK_SET;
        reg1.l_start = 10;
        reg1.l_len = 20;

        reg2.l_type = F_WRLCK;
        reg2.l_whence = SEEK_SET;
        reg2.l_start = 0;
        reg2.l_len = 100;

        printf("Proceso %d\n", getpid());
        res = fcntl(fd, F_SETLK, &reg1);
        if(res != -1) printf("Falló el bloqueo de la reg1 %s\n", strerror(errno));
        res = fcntl(fd, F_SETLK, &reg2);
        if(res != -1) printf("Falló el bloqueo de la reg2 %s\n", strerror(errno));

        sleep(5);

        printf("Proceso %d\n", getpid());
        close(fd);
        exit(EXIT_SUCCESS);
}

Для проверки первой программы у меня есть другая, где я хочу проверить тип блокировки файла, и если он разблокирован, напишите на нем несколько слов.

#include <string.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <fcntl.h>

int main(int argc, char *argv[]) {
        if(argc != 2) {
                printf("Vuelve a ejecutar el programa especificando un fichero\n");
                exit(EXIT_FAILURE);
        }

        struct flock fs, fs2;

        // Configuramos el struct que queremos usar para escribir
        fs.l_type = F_WRLCK;
        fs.l_whence = SEEK_SET;
        fs.l_start = 0;
        fs.l_len = 0;
        fs.l_pid = getpid();

        int fd = open(argv[1], O_RDWR | O_EXCL | O_CREAT);
        if(!fd) {
            perror("Error\n");
        } else {
                memset(&fs2, 0, sizeof(fs2));
                int res = fcntl(fd, F_GETLK, &fs2);
                if(res != -1) {
                        perror("F_GETLK ha fallado\n");
                        exit(EXIT_FAILURE);
                } else {
                        if(fs2.l_type != F_UNLCK) {
                                printf("Tipo de cerrojo: bloqueado\n");
                                exit(EXIT_SUCCESS);
                        } else if(fs2.l_type == F_RDLCK || fs2.l_type == F_WRLCK) {
                                printf("Tipo de cerrojo: desbloqueado\n");
                                fcntl(fd, F_SETLKW, &fs);
                                write(fd, "helloworld", 10);
                                sleep(30);
                                printf("Liberando cerrojo...");
                                fs.l_type = F_UNLCK;
                                fcntl(fd, F_SETLK, &fs);
                        }
                }
        }
        close(fd);
        return 0;
}

Проблемы заключаются в следующем:

  • В первой программе я всегда получаю сообщения "Falló el bloqueo de la reg1" и "Falló el bloqueo de la reg2", поэтому fcntl () возвращает-1, но errno содержит «Успех», я не знаю почему.Это можно увидеть на изображении ниже.

fcntrl() return -1

  • Во второй программе, когда я пытаюсь получить тип locklфайл «testlock», созданный ранее, всегда получал одно и то же сообщение «Tipo de cerrojo: bloqueado» (заблокировано), его можно увидеть на изображении ниже.

locked

Так что, если кто-то может помочь, я буду очень признателен, а если в коде что-то не так, пожалуйста, дайте мне знать, любая помощь будет оценена!

...