简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM