How to check if a file is locked or not?

拟墨画扇 提交于 2019-12-10 13:25:37

问题


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 */
}

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/21917962/how-to-check-if-a-file-is-locked-or-not

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!