创建进程树

Creating a process tree

以下程序应创建深度为 K 的进程树,每个节点上有 N 个子节点。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

void spawnNodes(int curLevel, int levelLimit, int childrenNumber, 
                int nodeNumber, int offset)
{
    if (curLevel == levelLimit)
        exit(0);

    curLevel++;
    printf("(%d, %d) Pid: %d with parent %d\n", curLevel, nodeNumber, 
            getpid(), getppid());

    for (int i = 0; i < childrenNumber; i++)
    {
        pid_t childPid = fork();
        if (childPid == -1)
        {
            perror("Couldn't create process");
            exit(1);
        }

        if (childPid == 0)
        {
            spawnNodes(curLevel, levelLimit, childrenNumber, offset + i, 
                       offset + i);
        }
        else
        {
            wait(NULL);
        }
    }
}

int main()
{
    int levelLimit, children;
    scanf("%d %d", &levelLimit, &children);

    spawnNodes(0, levelLimit, children, 0, 0);

    return 0;
}

乍一看可能是正确的。但是,有一种我不明白的奇怪行为。进程 1 的第一个儿子比它的最后一个儿子更深一层。

这就是我的意思:

p1--p2---p3--exit(0)
     \---p4--exit(0)
      \--p5--p6--exit(0)

我在 gdb 中调试时发现了这一点。此外,这是深度为 2:

的二叉树的输出
(1, 0) Pid: 5562 with parent 2835
(2, 0) Pid: 5563 with parent 5562
(2, 1) Pid: 5566 with parent 5563
(2, 1) Pid: 5569 with parent 5562

我做错了什么?

What am I doing wrong?

如果要创建Nchildren到一个进程没有创建进程wait()在创建第一个child后

]

为了更好地理解发生了什么,改变这个

if (curLevel == levelLimit)
  exit(0);

成为

if (curLevel == levelLimit) 
  pause(); 

此更改将使每个 child 继续存在,直到它被明确杀死。这样做 no 调用 wait() 将预先 return。这样你会看到每个 parent 只创建一个 child。