6

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

2 回答 2

4

非常简单,只需使用 F_GETLK 而不是 F_SETLK 运行 fnctl。这会将指针处的数据设置为锁的当前状态,您可以通过访问 l_type 属性来查找它是否被锁定。

详情请见:http ://linux.die.net/man/2/fcntl 。

于 2014-02-21T14:29:06.113 回答
1

您还需要设为fl20 memset​​。否则当您使用fcntl(fd, F_GETLK, &fl2)perror失败时,您会在终端上看到这样的消息:

fcntl:无效的参数

我建议您perror在调试系统调用时使用 , 。

于 2015-08-01T21:13:35.203 回答