0
#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 
9
  • Did you alread try? Commented Oct 22, 2017 at 16:25
  • Remember that after 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 30 foos output. Am I right? (Of course, I assume that none of the fork()s fails...) Commented Oct 22, 2017 at 16:27
  • Interesting. I get different results if I just print to terminal vs. piping it to a file or a program like less or wc -l. I get 64 in wc -l. Commented Oct 22, 2017 at 16:36
  • Hmm, I compiled with gcc in cygwin, run, copied the output to notepad++ and got 30 lines (as expected). Commented Oct 22, 2017 at 16:38
  • 3
    Piping changes the output buffer from line buffered to full buffered, so fork duplicates also the buffer content. Commented Oct 22, 2017 at 16:45

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.