使用fork()的进程不均匀的树

时间:2012-05-13 13:40:13

标签: c fork

我必须在C中使用fork()构建一个进程树。我从标准输入中获取一系列数字(例如:1 5 0 3),这些数字告诉我每个节点有多少个子节点。如果我们采用这个例子然后根进程创建了1个子进程,那么这个子进程创建了5个自己的子进程,然后从这5个子进程中,第一个没有创建任何子进程,第二个就创建了3个子进程,然后我们已经完成了。完成此操作后,根进程会调用绘制树的pstree

以下是该示例的图片:

我的问题是如何从特定节点创建新孩子?一个需要创建0个新流程,下一个需要创建其中3个流程。我不知道如何区分,只有那个特定的孩子才能生孩子而不是全部孩子。此外,我不确定如何使用pstree,因为在pstree被调用时树通常已经消失。我知道我可以wait()让孩子先行,但最后一个孩子没有孩子等待,所以他们结束得太快。

我编写了创建示例的代码。需要有关如何针对不同输入进行概括的想法。也有人可以告诉我如何从这段代码调用pstree,因为我似乎无法让它工作。

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


int main() {

pid_t pid;
pid_t temppid;
pid_t temppid2;
int  root_pid;
int status;

root_pid = getpid();

pid = fork(); // creates a child from root
if (pid == 0) { // if child
    pid = fork(); // fork again (child#1)
    if (pid != 0) { // if not child of child#1
        temppid = getpid(); // get pid
        if (getpid() == temppid) { // create child#2
            pid = fork();
            if (pid == 0) {
                temppid2 = getpid();
                if (getpid() == temppid2) { // create child#1
                    fork();
                }
                if (getpid() == temppid2) { // create child#2
                    fork();
                }
                if (getpid() == temppid2) { // create child#3
                    fork();
                }
            }
        }
        if (getpid() == temppid) { // create child#3
            fork();
        }
        if (getpid() == temppid) { // create child#4
            fork();
        }
        if (getpid() == temppid) { // create child#5
            fork();
        }
    }
}
else {
    // create another child from root
    pid = fork();
        if (pid == 0) {
            // run pstree in this child with pid from root
        }
}

while (1) {
    sleep(1);
}
}

3 个答案:

答案 0 :(得分:1)

对于pstree,解决方案很简单 - 每个过程在完成应该的操作之后都会进入睡眠状态(例如,一分钟)。
然后,您可以使用pstree查看正在发生的事情。

为了分叉正确的次数,似乎问题在于解析输入,而不是分叉。
我开始编写读取输入的代码,而不是分叉,只打印您要创建的进程树。一旦你清楚了,它就不能正确地做叉子。

答案 1 :(得分:1)

仅测试您的应用创建的层次结构:

而不是放置

return 0; 

作为最后一句话放了一个

while (1)
  sleep(1);

这使得流程一直运行,直到您按Ctrl-C

启动应用程序后,使用另一个终端并发出pstree来检查应用程序创建的流程层次。

要清理(如果在linux上),请发出killall <app name>

答案 2 :(得分:0)

我的一个建议是,您使用fork的返回值来判断您的代码是否在子进程或父进程中运行。

相关问题