cunixfcntl

fcntl doesn't lock/unlock the files [Unix - C]


I'm trying to use fcntl lib (at UNIX c programming) to lock or unlock files but seems isn't lock and I don't know why. I don't receive any error, it looks like that the program doing the lock but actually i can read/write the file and isn't locked

    if (enter == 2){
    getchar ();
    int fd;
    struct flock lock;
    char file[20];
    printf ("Enter file name:");
    fgets(file,20,stdin);
    printf ("opening %s\n", file);
    //Open a file descriptor to the file
    fd = open (file, O_RDWR);
    printf ("locking\n");
    //Initialize the flock structure
    memset (&lock, 0, sizeof(lock));
    lock.l_type = F_WRLCK;
    //Place a write lock on the file
    fcntl (fd, F_SETLK, &lock);
    
    printf ("locked; hit Enter to unlock... ");
    //Wait for the user to hit Enter
    getchar ();
    printf ("unlocking\n");
    //Release the lock
    lock.l_type = F_UNLCK;
    fcntl (fd, F_SETLK, &lock);
    close (fd);

Solution

  • It's very bold of you to claim you have locked the file when you didn't check the result of fcntl.

    Anyway, that is the expected behaviour. All getting a lock does is prevent others from getting a lock.[1] It doesn't prevent anyone from reading from or writing to the file.


    1. A write lock prevents anyone from getting a lock, while a read lock only prevent write locks from being obtained.