简体   繁体   English

我不明白stdio缓冲如何与子进程交互

[英]I don't understand how stdio buffering interacts with child processes

I think the output should be first child process should be executed the second child then parent but on compiling it gives the first line of first child and then first line of second child then again second line of first child and second line of second child. 我认为输出应该是第一个子进程应该执行第二个孩子然后父进程但是在编译时给出第一个孩子的第一行然后第二个孩子的第一行然后再次第二个孩子的第二行和第二个孩子的第二行。 Here is the code in question: 这是有问题的代码:

#include<stdio.h>
int main() {
  int pid,dip;
  pid=fork();
  if(pid==0) {
    printf("1st child's process id is %d \n",getpid());
    printf("first child dead");
  } else {
    dip=fork();
    if(dip==0) {
      printf("2nd child process id is %d\n",getpid());
      printf("Second child dead");
    } else {
      printf("Child with pid %d died \n",wait(0));
      printf("Child with pid %d died \n",wait(0));
      printf("I am the parent");
    }
  }

  return 0;
}

The order of execution there is indeterminate. 那里的执行顺序是不确定的。 There are three processes, the parent, and two children. 有三个进程,父进程和两个子进程。 So there are 3! 所以有3个! = 6 possibilities in terms of what order they complete in. =就他们完成的顺序而言,有6种可能性。

If you run that code enough times, you'll see all 6 such possibilities, although there may be a tendency toward one or two in particular. 如果您运行该代码足够多次,您将看到所有这六种可能性,尽管可能会有一两个特别的倾向。

Since there are several printf() s -- one of which is not flushed with a newline -- in each process, there are more that just 6 possibilities WRT what order these lines appear in. Two lines from the same process will always be sequential (ie, the first will appear before the second) but a line from another process could appear in between them. 由于有几个printf() s - 其中一个没有用换行符刷新 - 在每个进程中,只有6种可能性WRT这些行出现的顺序。来自同一进程的两行总是顺序的(即,第一个将出现在第二个之前)但是来自另一个进程的一条线可能出现在它们之间。

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

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