我正在尝试创建一个进程树层次结构,它为树高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;
}
最佳答案
这是因为你在break
循环中有for
。在if (t1 != 0)
中。父进程在创建第一个子节点后循环。
而“约翰·布林格是对的,这是一种可怕的方式。您所做的是递归调用main
函数。你应该也可以在createProcess
中处理这个问题。
关于c - C语言中的过程树层次结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52156763/