【发布时间】:2015-10-28 12:25:52
【问题描述】:
我正在使用 fcntl 的 F_SETLKW 获取读取锁,然后尝试使用 fcntl 的 F_GETLK 从同一进程读取相同的锁。但结果不合适。下面是示例代码
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int fd;
struct flock fl;
if ( (fd = open("lockfile", O_RDWR)) == -1 ) {
perror("open");
return 1;
}
memset(&fl, 0, sizeof(struct flock));
fl.l_type = F_RDLCK; // Read lock
fl.l_start = 10; // lock on offset 2
fl.l_len = 1; // lock length
fl.l_whence = 0; // lock value from start
if ( fcntl(fd, F_SETLKW, &fl) == -1 )
{
perror("fcntl:SETLK");
return 1;
}
printf("Read Lock successfull\n");
if ( fcntl(fd, F_GETLK, &fl) == -1 )
{
perror("fcntl:GETLK");
return 1;
}
printf("%d %d %d\n", F_RDLCK, F_WRLCK, F_UNLCK);
printf("Lock Type : %d\n", fl.l_type);
printf("Lock pid : %d\n", fl.l_pid);
printf("Lock offset : %d\n", fl.l_start);
close(fd);
return 0;
}
结果:
Read Lock successfull
0 1 2
Lock Type : 2
Lock pid : 0
Lock offset : 10
它返回锁类型为 2 (F_UNLCK) 并且它不返回获取锁的进程的 pid。
【问题讨论】:
-
发布的代码没有完全编译。建议在编译时始终启用所有警告,然后修复这些警告。 (对于 gcc,至少使用:
-Wall -Wextra -pedantic)
标签: c linux unix locking fcntl