我有以下代码,想要检查文件是否被锁定。如果没有被锁定,则要写入它。 我在两个终端上同时运行此代码,但每次都会在两个终端中得到“locked”状态,即使我没有将其锁定。 以下是代码:
#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 */
}
F_GETLK
已经在发布的代码中设置了,原始帖子没有被编辑。你能解释一下答案吗?我无法想象为什么这个答案被接受了?有什么我没注意到的东西吗? - Anubis