I have the following code:
for(i=1; i<=2; i++)
{
fork();
printf("x ");
}
I calculated that x should be printed out 6 times: twice in the first iteration and 4 times in the second.
Instead, X is printed 8 times. Why?
I have the following code:
for(i=1; i<=2; i++)
{
fork();
printf("x ");
}
I calculated that x should be printed out 6 times: twice in the first iteration and 4 times in the second.
Instead, X is printed 8 times. Why?
Because of buffering. Usually, stdout
is line-buffered, so
printf("x ");
doesn't immediately write the "x "
to the terminal but to the output buffer. That is copied when the process fork()
s, so each of the four processes after the second iteration has two "x "
in the output buffer [one from the parent/before forking in the first iteration, one from the second iteration] when it exits and eight x
s are printed altogether.
Flush the buffer immediately after the printf("x ");
and only six will be printed.