如何在C中解决这个fork()示例

编程入门 行业动态 更新时间:2024-10-23 20:20:56
本文介绍了如何在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()示例

本文发布于:2023-10-09 06:19:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1474938.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:示例   如何在   fork

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!