该程序创建了多少个进程,包括初始父进程?

Fre*_*eek 3 c fork

我正在试图弄清楚这个程序创建了多少个进程,包括初始父进程.正确的答案应该是9,但我不明白为什么答案是9.如何创建这9个流程?提前致谢!

#include <stdio.h>
#include <unistd.h>
…
int main()
{
  pid_t john;
  john = fork( );

  if (john == 0) {
      fork( ); fork( ); fork( );
  }
/* Consume resources of another process */
/* This does NOT create a new process. */
Consume( ); Consume( );

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

Kev*_*vin 8

请记住,fork();fork();fork();父母和孩子都在下一个叉子上.

main
 |
 |\          john = fork()
 | \ 
 |  \ 
 |  |\              fork()
 |  | \-----\  
 |  |\      |\      fork()
 |  | \     | \
 |  |  \    |  \
 |  |   \   |   \
 |  |\  |\  |\  |\  fork()
 |  | | | | | | | |
 1  2 3 4 5 6 7 8 9
Run Code Online (Sandbox Code Playgroud)


Yu *_*Hao 6

  john = fork( ); //fork a new process, we have 2 now.

  if (john == 0) {// child process go in the if statement
      fork( );   //child process fork to 2 processes
      fork( );   //2 processes continue to fork,so we have 2 more. 
      fork( );   //4 processes continue to fork, so we have 4 more.
  }
  //up to here, the child process of the first fork is now 8 processes
  //adding the first parent process, that is 9 in total.
Run Code Online (Sandbox Code Playgroud)