在 APUE 第 8.3 节fork function
中,关于父进程和子进程之间的文件共享,
它说:It is important that the parent and the child share the same file offset.
在第 8.9 节中Race Conditions
,有一个例子:父母和孩子都写入
一个在调用 fork 函数之前打开的文件。该程序包含一个竞争条件,
因为输出取决于内核运行进程的顺序以及每个进程运行的时间。
但是在我的测试代码中,输出是重叠的。
[Langzi@Freedom apue]$ cat race.out
this is a long long outputhis is a long long output from parent
似乎父项和子项具有单独的文件偏移量,而不是共享相同的偏移量。
我的代码有错误吗?还是我误解了共享偏移量的含义?
任何建议和帮助将不胜感激。
以下是我的代码:
#include "apue.h"
#include <fcntl.h>
void charatatime(int fd, char *);
int main()
{
pid_t pid;
int fd;
if ((fd = open("race.out", (O_WRONLY | O_CREAT | O_TRUNC),
S_IRUSR | S_IWUSR)) < 0)
err_sys("open error");
if ((pid = fork()) < 0)
err_sys("fork error");
else if (pid == 0)
charatatime(fd, "this is a long long output from child\n");
else
charatatime(fd, "this is a long long output from parent\n");
exit(0);
}
void charatatime(int fd, char *str)
{
// try to make the two processes switch as often as possible
// to demonstrate the race condition.
// set synchronous flag for fd
set_fl(fd, O_SYNC);
while (*str) {
write(fd, str++, 1);
// make sure the data is write to disk
fdatasync(fd);
}
}