简体   繁体   English

在此C程序中,fork()如何工作?

[英]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. 这将打印“ foo” 30次。 Why? 为什么?

And why does it print "foo" 64 times if you pipe the output? 而且,如果通过管道传输输出,为什么它会打印“ foo” 64次?

$ ./a.out | wc -l
64

When you invoke fork() everything gets duplicated. 当您调用fork()所有内容都会重复。 So you will double in each iteration. 因此,您将在每次迭代中加倍。 That's why it prints 2+4+8+16=30 times. 这就是为什么它会打印2 + 4 + 8 + 16 = 30次的原因。 This can be easily seen if you print the value of i together with the PID for the process. 如果将i的值与该过程的PID一起打印,则可以很容易看出这一点。

As mch stated, piping changes the output buffer from line buffered to full buffered, so fork duplicates also the buffer content. 如mch所述,管道会将输出缓冲区从行缓冲更改为全缓冲,因此fork也会复制缓冲区内容。 That's why you get 64 printouts. 这就是为什么您获得64个打印输出的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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