理解fork()的语句及其进程树 [英] Understanding the fork() statement and its process tree

查看:1579
本文介绍了理解fork()的语句及其进程树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出有多少流程与下面的C code创建:

I am trying to figure out how many processes are created with the following C code:

int main ()
{
   fork();
   if (fork()) {
      fork();
   }
   fork();
   return 0;
}

有几件事情我感到困惑:

There are a couple of things I am confused about:

每个时间fork()的调用,请问孩子从code开始启动,或者它启动,其中电流fork()的从创建它?举例来说,如果第3行的第一个叉被调用时,我会在4号线,或1号线开始了孩子?我相信这是一个愚蠢的问题,B / C,将创建一个无限循环,如果每个孩子从一开始就开始了,但我想这个假设是安全的。

Each time fork() is called, does the child start from the start of the code, or does it start where the current fork() created it from? For instance, if line 3's first fork is called, will I start the child at line 4, or line 1? I believe this is a stupid question, b/c it would create an infinite loop if each child started from the beginning, but I want to be safe about this assumption.

接下来,当叉叫,难道当前进程分成两个新的流程,一个是父母,而其他的孩子,或者是自动父当前的进程,所以真的,创建只是一个额外的进程。

Next, when fork is called, does the current process split into two NEW processes, one being the parent, and the other the child, or is the current process automatically the parent, so really, just one extra process is created.

最后,if语句,我当它实际上是父母,总是0时,它是孩子pretty一定叉返回父id的值。所以,我是正确的假设,if语句将是错误的每一个儿童催生了?

Lastly, with the if statement, I am pretty certain fork returns the value of the parent id when it is actually the parent, and always 0 when it is the child. So, am I correct to assume that the if statement will be false for every child spawned?

使用我的上述假设,这就是我想出的进程树,并会如果有人认为这是把它扔了故障大大AP preciate。孩子们在树重新present数量code。该叉正在发生的行:

With all my assumptions above, this is the process tree I came up with, and would greatly appreciate if someone sees a fault that is throwing it off. The number of the children in the tree represent the line of code that the fork is currently happening:

        main
  |    |    |    |
  3    4    5    7    // the main/initial process calls fork 4 times
| | |  |    |    
4 5 7  7    7         // the first fork will see 3 additional forks since it was called
| |                   // at line 3 and I assume resumes at line 4.
7 7                   // The second and third original children would each only callthe
                      // very last fork().  The last fork has no other forks following.

因此​​,有创造(包括主)10总流程。难道我错了?

Therefore, there are 10 total processes created (including main). Did I do it wrong?

推荐答案

(1)线直接在后叉

(2)一个新进程。孩子是父母的一个副本。

(2) One new process. The child is a copy of the parent.

(3)返回的孩子的PID在孩子家长和0。 if语句将是每一个孩子假的。它应该出来12道工序。我在可怕绘制图表,但你应该能够找到答案。

(3) fork returns the child's pid in the parent and 0 in the child. The if statement will be false for every child. It should come out to 12 processes. I'm terrible at drawing graphs but you should be able to figure it out.

这篇关于理解fork()的语句及其进程树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆