我写了一个简单的代码来测试 flock():
int main (int argc, char * const argv[]) {
int fd1;
if (fd1 = open( "file1", O_RDWR | O_CREAT | O_TRUNC) == -1)
{
perror("Cannot open file 1.\n");
fflush(stdout);
}
else
{
printf("file opened 1.\n");
fflush(stdout);
}
if(flock(fd1,LOCK_EX)==0)
{
printf("THE FILE WAS LOCKED 1.\n");
}
else if(errno == EACCES)
{
printf("The file is locked 1.\n");
}
std::cout<<"Enter any key:"<<std::endl;
std::cin >> input;
close(fd1);
std::cout<<"Lock was released."<<std::endl;
return 0;
}
当我运行可执行文件“Alex”两次时:
第一个过程:
$ ./Alex
file opened 1.
THE FILE WAS LOCKED 1.
Enter any key:
第二个过程:
$ ./Alex
file opened 1.
THE FILE WAS LOCKED 1.
Enter any key:
在事件监视器中,我看到两个具有两个不同 PID 的 Alex 实例。
似乎 flock() 不起作用。我错过了什么?谢谢!
最佳答案
尝试:
if ((fd1 = open( "file1", O_RDWR | O_CREAT | O_TRUNC)) == -1)
// ^ ^
因为你写的是一样的:
if (open( "file1", O_RDWR | O_CREAT | O_TRUNC) == -1)
fd1 = TRUE;
else
fd1 = FALSE;
因此,您正试图锁定 stdin
或 stdout
(取决于 open()
的结果)。
关于c - flock() 不会阻止其他进程获得独占锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26888728/