#include <stdio.h> #include <unistd.h> int main(void) { int i = 0; for (i = 0; i < 4; i++) { fork(); printf("foo\n"); } return 0; } This prints "foo" 30 times. Why?
And why does it print "foo" 64 times if you pipe the output?
$ ./a.out | wc -l 64 When you invoke fork() everything gets duplicated. So you will double in each iteration. That's why it prints 2+4+8+16=30 times. This can be easily seen if you print the value of i together with the PID for the process.
As mch stated, piping changes the output buffer from line buffered to full buffered, so fork duplicates also the buffer content. That's why you get 64 printouts.
fork()two processes exist with the same values in variables. Thus, in each iteration of the loop the number of processes should duplicate. This is 2 + 4 + 8 + 16 = 30. I would expect 30foos output. Am I right? (Of course, I assume that none of thefork()s fails...)