I have the following code where I want to check if the file is locked or not. If not then I want to write to it. I am running this code by running them simultaneously on two terminals but I always get "locked" status every time in both tabs even though I haven't locked it. The code is below:

#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int main()
{
    struct flock fl,fl2;
    int fd;

    fl.l_type   = F_WRLCK;  /* read/write lock */
    fl.l_whence = SEEK_SET; /* beginning of file */
    fl.l_start  = 0;        /* offset from l_whence */
    fl.l_len    = 0;        /* length, 0 = to EOF */
    fl.l_pid    = getpid(); /* PID */

    fd = open("locked_file", O_RDWR | O_EXCL | O_CREAT);
    fcntl(fd, F_GETLK, &fl2);
    if(fl2.l_type!=F_UNLCK)
    {
        printf("locked");
    }
    else
    {
        fcntl(fd, F_SETLKW, &fl); /* set lock */
        write(fd,"hello",5);
        usleep(10000000);
    }
    printf("\n release lock \n");

    fl.l_type   = F_UNLCK;
    fcntl(fd, F_SETLK, &fl); /* unset lock */
}
有帮助吗?

解决方案

Very simple, just run fnctl with F_GETLK instead of F_SETLK. That will set the data at your pointer to the current state of the lock, you can look up if it is locked then by accessing the l_type property.

please see: http://linux.die.net/man/2/fcntl for details.

其他提示

You also need to fl2 to be memset to 0. Otherwise when you use fcntl(fd, F_GETLK, &fl2) and perror on failure, you will see a message as such on the terminal:

fcntl: Invalid Arguement

I recomend that you use perror, when debugging system calls.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top