我正在尝试创建一个递归函数,在给定树的级别数的情况下,使用 fork() 创建父子进程的二叉树结构。到目前为止我已经:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
void createTree(int level){
pid_t leftson;
pid_t rightson;
if (level > 1){
if ((leftson = fork()) < 0) {
perror("fork:");
exit(1);
} // Create the first son
if (leftson == 0){
createTree(level--);
} // If I'm the left son, continue biulding the structure
else { // I'm father
if ((rightson = fork()) < 0) {
perror("fork:");
exit(1);
} // Create right son
if (rightson == 0){
createTree(level--);
} // I'm right, continue building
else printf("created my 2 sons"); // I'm the father
}
}
else if (level == 1){
printf("end of tree");
}
}
void main(){
createTree(3);
}
问题是程序进入了创建进程的无限循环,因为级别变量永远不会减少,我正在考虑使用管道,但我不知道当进程太多时如何使用它们。
另外,有没有办法像我在 bash 中那样给出新进程的参数?而不是使用管道?
最佳答案
尝试使用createTree(level-1);
而不是createTree(level--);
,因为有时这可能会导致递归调用中的无限循环。
关于c - 进程的二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26319803/