【发布时间】:2016-05-15 10:49:57
【问题描述】:
以下程序应创建深度为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
我做错了什么?
【问题讨论】:
标签: c linux recursion fork waitpid