当前位置: 动力学知识库 > 问答 > 编程问答 >

c - 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:

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),

0 being primary parent from which it starts forking

1 being 2 childs of the parent in 0

2 being 4 childs of the 2 parents in 1

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?

  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. Thus, the parent's instance of cCount will never increment, so the loop will run forever.

分享给朋友:
您可能感兴趣的文章:
随机阅读: