我正在尝试创建一个进程树层次结构,为树的高度 H 创建 C 个子进程。我编写了以下代码,但每个进程只创建一个子进程。我哪里错了?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
void createProcess(int height,int children){
int root, parent, t1, t2, t3, i, pid, status;
root = getpid();
parent = getppid();
printf("%d: Process starting\n", root);
printf("%d: Parent's id = %d\n", root, parent);
printf("%d: Height in the tree = %d\n", root, height);
printf("%d: Creating %d children at height %d\n", root, children, height - 1);
char c[4], h[4];
sprintf(h, "%d", height - 1);
sprintf(c, "%d", children);
char *args[] = {"./forkk", h, c, NULL};
for (i = 0; i < children; i++) {
t1 = fork();
if (t1 != 0) {
printf("child pid %d parent pid %d\n", getpid(), getppid());
break;
}
if (t1 == 0) {
execvp("./forkk", args);
}
}
pid = wait(&status);
sleep(5);
//printf("%d Terminating at Height %d\n",root,height);
}
int main(int argc, char** argv) {
int i;
printf("No of Arguments: %d\n", argc);
for (i = 0; i < argc; i++) {
printf("%s\n", argv[i]);
}
int height = atoi(argv[1]);
int children = atoi(argv[2]);
printf("Height %d\n", height);
printf("Children %d\n", children);
if (height > 1)
createProcess(height, children);
return 0;
}
最佳答案
这是因为在 for
循环中有 break
。在 if (t1 != 0)
中。父级在创建第一个子级后退出循环。
@John Bollinger 是对的,这样做很糟糕。您正在做的是递归调用 main
函数。您应该并且可以在 createProcess
中处理这个问题。
关于c - C 中的进程树层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52156763/