In the APUE 8.3 section fork functionon file sharing between parent and child processes,
He said:It is important that the parent and the child share the same file offset.
And in section 8.9 Race Conditionsthere is an example: both parent and child records are written to a
file that opens before calling the fork function. The program contains a race condition,
because the output depends on the order in which the processes are started by the kernel and how long each process takes.
But in my test code, the output is overlapping.
[Langzi @Freedom apue] $ cat race.out
is a long long output from a parent, this is a long long output from a parent
It seems that the parent and child have separate file offsets instead of using the same offset.
Is there an error in my code? Or did I misunderstand the meaning of the bias exchange?
Any advice and help would be appreciated.
the 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)
{
set_fl(fd, O_SYNC);
while (*str) {
write(fd, str++, 1);
fdatasync(fd);
}
}
source
share