我读了一本关于 Linux 文件的书,它给出了下一个例子:
int main(char ** argv, int argc) {
int stat;
int fd = open("dugma1.txt", O_WRONLY, 0666);
if (fork() == 0) {
int fd2 = open("dugma1.txt", O_WRONLY, 0666);
sleep(10);
if (lockf(fd2, F_TLOCK, 17) >= 0) {
write(fd2, "I was here second", 17);
}
} //if
else {
lockf(fd, F_TLOCK, 16);
write(fd, "I was here first", 16);
wait(&stat);
}
}
它说输出将是: I was here first
,原因是:我们不关闭文件。但我不明白这个解释。我们先写:I was here first
,但是为什么后面sleep(10)
我们就不去这部分代码了:
if (lockf(fd2, F_TLOCK, 17) >= 0) {
write(fd2, "I was here second", 17);
}
F_TLOCK
是一个非阻塞的,为此我们将成功地写出“我是第二个”。
谢谢