Bob
Bob

Reputation: 761

How does fork() work here in this C program?

#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

Upvotes: 0

Views: 207

Answers (1)

klutt
klutt

Reputation: 31429

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.

Upvotes: 1

Related Questions