简体   繁体   中英

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! = 6 possibilities in terms of what order they complete in.

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.

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