gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:34:44 25 4
gpt4 key购买 nike

我必须在C中使用fork()构造一个进程树。我从标准输入中得到一个数字序列(例如:1 5 0 3),这些数字告诉我每个节点有多少个子代。如果以该示例为例,则根进程将创建一个孩子,然后这个孩子将创建自己的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);
}
}

最佳答案

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

对于正确的次数进行分叉,似乎问题在于解析输入,而不是分叉。
我将从编写读取输入的代码开始,而不是分叉,而只是打印要创建的进程树。弄清这一点后,就不能正确进行分叉了。

关于c - 使用fork()的进程树不均匀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10572218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com