我在我的ubuntu机器上执行了以下c代码.我读过关于fcntl()用于锁定文件的内容,如果F_WRLCK opton被设置为...so,即使不允许读取,也不允许读取。在放弃锁定之前,我通过按enter键,尝试以两种方式打开文件--直接双击file1.cpp,以及在新的terminal...both中运行不同的c程序,当文件是opened...so时,fcntl()如何允许在设置F_WRLCK时打开这些文件.
int main(int argc, char *argv[])
{
struct flock fl = {F_WRLCK, SEEK_SET, 0, 0, 0 };
int fd;
fl.l_pid = getpid();
if ((fd = open("/home/file1.cpp", O_WRONLY)) == -1)
{
perror("open");
exit(1);
}
if (fcntl(fd, F_SETLKW, &fl) == -1)
{
perror("fcntl");
exit(1);
}
printf("Press <RETURN> to release lock: ");
getchar();
fl.l_type = F_UNLCK; /* set to unlock same region */
if (fcntl(fd, F_SETLK, &fl) == -1)
{
perror("fcntl");
exit(1);
}
printf("Unlocked.\n");
close(fd);
return 0;
}发布于 2012-06-16 11:15:47
fcntl锁纯粹是咨询锁。它们的唯一的效果是在无法获得锁时导致fcntl F_SETLK调用阻塞。它们对IO操作没有任何影响。当需要同步时,应该由您的程序在执行IO之前获得所需的锁。
这完全类似于使用互斥保护内存中的对象。互斥锁不会阻止您读取或写入内存地址;它只是一种协议,用于确保您的程序只读和写以及正确的时间。
https://stackoverflow.com/questions/11062880
复制相似问题