I’m learning to work with fork(), and I have some questions.
Consider the following code:
#include <stdio.h>
#include <unistd.h>
int main()
{
int i;
for(i = 0; i < 5; i++)
{
printf("%d", i);
if((i%2)==0)
if(fork())
fork();
}
}
When I output to a terminal, I get the result I expect (i.e.: 0,1,1,1,2,2,2,...). But when I output to a file, the result is completely different:
-
Case 1: (output to terminal, e.g.:
./a.out):Result is:
0,1,1,1,2,2,2,... -
Case 2: (output to file, e.g.:
./a.out > output_file)Result is:
0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,...
Why it is like this?
When you output to a file, the stdio library automatically block-buffers the outbound bits.
When a program calls
exit(2)or returns frommain(),any remaining buffered bits are flushed.In a program like this that doesn’t generate much output, all of the I/O will occur after the return from
main(),when the destination is not a tty. This will often change the pattern and order of I/O operations all by itself.In this case, the result is further complicated by the series of
fork()calls. This will duplicate the partially filled and as-yet-unflushed I/O buffers in each child image.Before a program calls
fork(),one might first flush I/O using fflush(3). If this flush is not done, then you may want all processes except one (typically: the children) to_exit(2)instead ofexit(3)or return frommain(),to prevent the same bits from being output more than once. (_exit(2) just does the exit system call.)