简体   繁体   English

分叉二叉树,派生功能问题

[英]Forking a binary tree, fork functionality issue

Ok, So i've been looking this all over stackoverflow, and definitely googling for a good half an hour, but the answers I seem to get have barely anything to do with what I actually want to do, hopefully someone will help me on this one, heres the code: 好的,所以我一直在stackoverflow上寻找这些内容,并且肯定搜索了半个小时,但是我似乎得到的答案与我实际上想要做的事情几乎没有任何关系,希望有人可以在此方面为我提供帮助一,这是代码:

int cCount = 0;

while(cCount < 2)
{
    switch(fork())
    {
    case 0:
    cCount++;
    break;

    case -1:
    printf("Failed");
    break;

    default:
    break;
    }
}

return;

Now for the questions that arise, this code is suppose to create a tree that has 3 levels (0,1,2), 现在针对出现的问题,此代码假定创建一个具有3个级别(0,1,2)的树,

0 being primary parent from which it starts forking 0是从其开始分叉的主要父级

1 being 2 childs of the parent in 0 1是0中父母的2个孩子

2 being 4 childs of the 2 parents in 1 2是1中2个父母中的4个孩子

Creating a symmetric tree. 创建对称树。 Essentially though I have a few questions: 本质上,尽管我有几个问题:

  1. Switch executes fork on every loop, so in theory if fork > 0, it will still be forked creating a sub child for a parent and the loop will keep going, therefore it might end up with a chain parent-parent-parent-parent, instead of 2 children per parent, then 4 for 2 etc. How does fork knows what to do? Switch在每个循环上执行fork,因此从理论上讲,如果fork> 0,它仍将被派生,为父级创建一个子子级,并且该循环将继续进行,因此最终可能会产生一个链parent-parent-parent-parent,而不是每个父母2个孩子,然后2个孩子中的4个,等等。fork如何知道该怎么做?

  2. Say I want to do a tree that has one more child attached to it at the last layer (level) for example, how would I start? 假设我想做一棵在最后一层(级别)上附加了一个孩子的树,那么我将如何开始?

Do I understand fork correctly? 我能正确理解叉子吗? Please explain if not, theres quite alot of tutorials around the net, but they all seem to make it way more complicated than it might be. 如果没有的话,请解释一下,网络上有很多教程,但是它们似乎都使它变得比可能更复杂。

Cheers, thanks And be kind to me, english is not my native tongue. 干杯,谢谢,对我好一点,英语不是我的母语。

This code will basically fork bomb, and here's why: 这段代码基本上会产生分叉炸弹,这是为什么:

When the process hits the first fork , it'll return 0 for the child, and a positive number (the PID of the child) for the parent. 当进程到达第一个fork ,它将为子级返回0,并为父级返回一个正数(子项的PID)。 Thus, the parent's instance of cCount will never increment, so the loop will run forever. 因此,父级的cCount实例将永远不会增加,因此循环将永远运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM