当我运行程序时:
int i = fork();
if (!i){
int id = open("shared.txt", 0600 | O_WRONLY);
if(flock(id, LOCK_EX | LOCK_NB) == -1)
perror("flock_ch");
if(write(id, "child", 5)) printf("child did it\n");
else perror("write_ch");
sleep(3);
close(id);
}
else {
int id = open("shared.txt", 0600 | O_WRONLY);
if(flock(id, LOCK_EX | LOCK_NB) == -1)
perror("flock_PR");
if(write(id, "parent", 6)) printf("parent did it\n");
else perror("write_pr");
sleep(3);
close(id);
}
wait(NULL);
我希望只有一个进程会在文件中写入一些内容,但即使文件被锁定,也会有两个进程写入文件。
1条答案
按热度按时间u2nhd7ah1#
由于忽略了
flock()
的错误返回值,两个进程都在写入文件。flock_ch: Resource temporarily unavailable
是因为flock()
返回错误并告诉您文件被锁定。您打印了错误消息,但没有对错误消息做出响应。您可能需要(a)退出或(b)循环,直到flock()
成功。使用循环可能类似于:
运行上述命令将生成:
或者,删除
LOCK_NB
标志,这样flock()
就会阻塞,直到锁可用为止。运行上述命令将生成: