如何在C中解决这个fork()示例 [英] How to solve this fork() example in c

查看:72
本文介绍了如何在C中解决这个fork()示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int x=0;
int main()
{
  for(i=0;i<2;i++)
  {
    fork();
    x=x+5;
  }
  return 0;
}

我是fork()概念的新手.上面的树(具有x值)是否是上述C代码的正确解决方案?节点中的值分别是其进程的x值.

I am a newbie to the fork() concept. Is the above tree (with x values) a correct solution for the C code mentioned above? The values in the nodes are the x values of their processes respectively.

我们还可以从子流程中将值返回给父流程吗?假设在上面的示例代码中,我可以将子级的x值返回给父进程吗?

And also can we return values to the parent process from the child process? Suppose in the above example code can I return the x value of the child to the parent process?

推荐答案

您的意思是那是一个进程树,气泡中的x的值是?那不,那是不正确的.

You mean that's a process tree and in the bubbles is the value of x? Then no, that's not correct.

生成一个孩子时,它会得到父对象的精确副本...所以让我们打印"一些值,以便我们可以看到事物的状态(我正在为所有事物组成PID)

When a child is spawned, it gets an exact copy of the parent... so let's "print" some values so we can see the state of things (I'm makeing up PIDs for everything)

开始时,它只是父项:

parent (11174) x = 0, i = 0

然后我们点击fork(),现在我们有两个过程:

Then we hit the fork(), now we have two processes:

 +--parent (11174) x = 0, i = 0
 |
 +->child1 (11175) x = 0, i = 0

接下来的数学:

 parent (11174) x = 5, i = 0

 child1 (11175) x = 5, i = 0

当我们循环备份时,我们的i将增加,并且每个进程现在都运行循环并命中fork():

When we loop back up, our i's will be incremented, and each process now runs the loop and hits fork():

 +--parent (11174) x = 5, i = 1
 |
 +->child2 (11176) x = 5, i = 1

 +--child1 (11175) x = 5, i = 1
 |
 +->child  (11177) x = 5, i = 1

现在每个人都再次数学:

Now everyone hits the math again:

 parent (11174) x = 10, i = 1

 child2 (11176) x = 10, i = 1

 child1 (11175) x = 10, i = 1

 child  (11177) x = 10, i = 1

最后,每个人都进入循环并增加i的循环.因此,您的最终结果是:

Finally everyone hits the loop and increments i breaking from it. So your end result is:

 parent (10)----->child1(10)---->child(10)
           |
           +----->child2(10)

这篇关于如何在C中解决这个fork()示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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