- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我必须在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/
我需要在半径R的圆内生成一个均匀随机点。 我意识到,通过在区间 [0 ... 2π) 中选择均匀随机的角度,并在区间 (0 ... R) 中选择均匀随机的半径,我最终会得到更多的点朝向中心,因为对于两
我想在一个正方形内生成 N 个点(均匀地)。我怎样才能做到这一点? 最佳答案 非常酷的问题,比我想象的要困难得多,但这就是想法。有关于 n 边形的论文,但我只会做正方形。因此,圆的均匀分布是一个常见问
考虑以下示例: import itertools import numpy as np a = np.arange(0,5) b = np.arange(0,3) c = np.arange(0,7)
SQL Server 将一组值分成 5 组,每组的 sum(count) 应该均匀分布。 表仅包含 2 列 rid 和 count。 create table t1(rid int, count in
我有以下简单的 HTML。 A B C 和 CSS: ul { width: 100%; display: flex; flex-direction:
我是一名优秀的程序员,十分优秀!