C ++中的嵌套fork()树

nested fork() tree in c++

到目前为止我已经完成了:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int p1,p2,p3,p4,i;
    int left,leftPid;
    int right;  
    left=fork();
    right=fork();
    for(i=0;i<=2;i++)
    {
        if(left==0)
            printf("\nleft Child Process. Level: %d | myPID: %d | myParent: %d\n",i,getpid(),getppid());    
        else
            leftPID=left;
        if (right==0)
        {
            printf("\nright Child Process. Level: %d | myPID: %d | myParent: %d\n",i,getpid(),getppid());
            right=fork();
        }
        else
        {
            printf("\nParent Process. Level %d | My left Child: %d | My right Child: %d | myPID: %d\n",i,leftPID,right,getpid());
        }
    }
}

我需要这样的输出:

left Child Process. Level: 1 | myPID: 23560 | myParent: 23559

Parent Process. Level: 0 | My left Child: 23560 | My right Child: 23561 | myPID: 23559

left Child Process. Level: 2 | myPID: 23562 | myParent: 23561

left Child Process. Level: 3 | myPID: 23564 | myParent: 23563

right Child Process. Level: 3 | myPID: 23565 | myParent: 23563

Parent Process. Level: 2 | My left Child: 23564 | My right Child: 23565 | myPID: 23564

Parent Process. Level: 1 | My left Child: 23562 | My right Child: 23563 | myPID: 23561

这是我需要的树形表示:

而且我做的代码和我需要的相差甚远。我希望有人能帮助我。

这是错误的:

left=fork();
right=fork();

在这段代码之后,您最终会得到四个进程 - 因为每个 fork() 的进程都会立即再次分叉 - 为什么要有三个。您需要确保检查 each 分叉调用的结果。

考虑到这一点,您可以重新编写其他代码。

首先要记住的是,当调用fork()时,它下面的代码由child和parent执行。因此,您确实需要通过使用 fork() 系统 call.Now 的返回值来为它们设置条件,在调用 left=fork() 之后,将执行下一条语句 right=fork() by parent,这是对的,但是同样的语句也被 left child 执行,你不希望这样!所以在使用left=fork()系统调用后,给leftchild和parent加上条件,让它们执行各自对应的代码路径。您的代码中的另一个错误是 right child 只会依次生成 right child 而不是 left child。

for(i=0;i<=2;i++)
{
    left=fork();
    leftPID=left; 

    if(left==0) //use break statement for left child since we want it to be kicked out and not execute anything!
    {
        printf("\nleft Child Process. Level: %d | myPID: %d | myParent:                      %d\n",i,getpid(),getppid())
        break; // break statement has to used here necessarily or else left child  will keep on making left childs
    }         
    else if(left>0) //this is executed by parent
    {
        right=fork(); //parent forks a right child

        if (right==0) //this is executed by right child
        {
            printf("\nright Child Process. Level: %d | myPID: %d | myParent:                      %d\n",i,getpid(),getppid());
        } 
        else if(right>0) //executed by parent
        {
            printf("\nParent Process. Level %d | My left Child: %d | My right Child: %d | myPID: %d\n",i,leftPID,right,getpid());
            break; //again use break to kick out parent since now this parent has no work to do and break statement has to used here necessarily or else parent will keep on making childs-left and right
        }
    }    
}