In APUE section 8.3 fork function
, about file sharing between parent and child processes,
It said: It is important that the parent and the child share the same file offset.
And in section 8.9 Race Conditions
, there is a example: both parent and child write to
a file which is opened before invoking fork function. The program contains a race condition,
because the output depends on the order in which the processes are run by the kernel and for how long each process runs.
But in my test code, the output are overlapped.
[Langzi@Freedom apue]$ cat race.out
this is a long long outputhis is a long long output from parent
It seems the parent and child have separate file offsets instead of sharing the same offset.
Is there any error in my code? Or did I misunderstand the meaning of sharing offset?
Any advice and help will be appreciated.
following is my code:
#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);
}
}