Hi,
Consider the following piece of code:
int main(void) {
int i;
pid_t pidp;
for (i=0;i<4;i++) {
switch (pidp=fork()) {
case -1:
fprintf(stdout, "Error during fork.\n");
exit (1);
case 0:
fprintf(stdout, "From child: I am born.\n");
exit (0);
default:
fprintf(stdout, "From parent: Child %d has ID %d.\n", i+1, pidp);
}
}
exit(0);
}
I understand that this program is not protected while it is writing to stdout. Therefore, certain inconsistencies are bound to happen. But I am not able to comprehend the following observation.
When I run this program, the output is on the standard output and is the following (as expected):
From child: I am born.
From parent: Child 1 has ID 6412.
From parent: Child 2 has ID 6413.
From child: I am born.
From child: I am born.
From parent: Child 3 has ID 6414.
From child: I am born.
From parent: Child 4 has ID 6415.
However, when the output is redirected to a file (even if "tee" is used), the output has a lot of duplicated lines:
From child: I am born.
From parent: Child 1 has ID 6454.
From child: I am born.
From parent: Child 1 has ID 6454.
From parent: Child 2 has ID 6455.
From parent: Child 3 has ID 6456.
From child: I am born.
From parent: Child 1 has ID 6454.
From parent: Child 2 has ID 6455.
From child: I am born.
From parent: Child 1 has ID 6454.
From parent: Child 2 has ID 6455.
From parent: Child 3 has ID 6456.
From parent: Child 4 has ID 6457.
I figure that it is due to the stdout stream becuase using fflush before the print statements in the code fixes this inconsistency.
But could somebody explain what's exactly happening?
regards,
Quantum Teleporter!