3

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?

ollo
  • 24,797
  • 14
  • 106
  • 155
Sorin
  • 908
  • 2
  • 8
  • 19
  • 2
    possible duplicate of [fork() and output](http://stackoverflow.com/questions/9364410/fork-and-output) – hmjd May 19 '13 at 14:25

1 Answers1

7

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 xs are printed altogether.

Flush the buffer immediately after the printf("x "); and only six will be printed.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431