3

我试图弄清楚这个程序创建了多少进程,包括最初的父进程。正确答案应该是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;
}
4

4 回答 4

8

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

main
 |
 |\          john = fork()
 | \ 
 |  \ 
 |  |\              fork()
 |  | \-----\  
 |  |\      |\      fork()
 |  | \     | \
 |  |  \    |  \
 |  |   \   |   \
 |  |\  |\  |\  |\  fork()
 |  | | | | | | | |
 1  2 3 4 5 6 7 8 9
于 2013-06-22T14:46:58.287 回答
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.
于 2013-06-22T14:44:03.890 回答
0

P1 分叉,创建 P2。P1 有john = <NOT ZERO>,P2 有john = 0。因此 P2 执行if. 它分叉,创建 P3。现在,P2 和 P3 在第二个分叉处。所以他们分叉,创建 P4 和 P5。现在 P2、P3、P4 和 P5 都只剩下一个叉子了。他们分叉,创建 P6、P7、P8 和 P9。总共产生了九个进程。

fork创建调用进程的程序映像的精确副本,除了它返回 0 给子进程和返回 PID 给父进程的事实。孩子将与父母在叉子后的位置相同。

于 2013-06-22T14:43:08.683 回答
0

朋友,我也在学习过程中。我得到了一些关于函数 fork() 的信息。要知道,fork 会创建一个新的子进程,它会从父进程中获取一份数据、内容、栈、堆等的副本,子进程也会从父进程中获取一份 PCB 的副本。程序的运行由包含程序指令的程序计数器控制。PCB 包含程序计数器的信息。由于子进程和父进程是同一个PCB,子进程会运行Program Counter的左边指令,所以在父进程中fork之前的代码不会在子进程中运行。在if语句中,当第一次fork运行时,子进程只会运行第二次和第三次fork。你可以用它来绘制流程图来帮助你解决这个问题。像这样。对不起,我不' 没有足够的声誉为您发布图像。希望我的话能帮到你。

于 2013-11-20T16:34:32.430 回答