C Tree Fork()递归

C Tree Fork()递归,c,recursion,tree,fork,C,Recursion,Tree,Fork,我试图使用Fork()的递归函数运行下面的树。但是,我只能生成前3个子树,对于树的其余部分,我丢失了正确的引用。 void进程树(int级别,char*child[],int n){ int i; int索引=子项[n]; int-myP; 智力状态; 如果(n>=级别){ 出口(0); }否则{ 对于(i=0;i

我试图使用Fork()的递归函数运行下面的树。但是,我只能生成前3个子树,对于树的其余部分,我丢失了正确的引用。

void进程树(int级别,char*child[],int n){
int i;
int索引=子项[n];
int-myP;
智力状态;
如果(n>=级别){
出口(0);
}否则{
对于(i=0;i[%d]\n\n”,getpid());
进程树(级别、子级、n);
}

看来您的递归终止提前退出了程序。对于递归,我通常使用“return”

void process_tree(int level, char *child[], int n){
int i;
int index = child[n];
int myP;
int status;

if(n >= level){
   exit(0);
} else {
    for (i=0; i < index; i++){
        myP = fork();
        switch(myP){
            case -1:
                printf("fork failed\n");
                break;
            case 0:
                printf("Son - %d de %d\n\n", getpid(), getppid());
                n++;
                process_tree(level, child, n);
                break;

            default:
                break;
        }
    }
    for (i=0; i< index; i++){
        wait(&status);
    }
}
}

int main(){
int level = 4;
int n = 0;
int child [] = {3, 2, 1, 1};
printf("[Father] -> [%d]\n\n", getpid());
process_tree (level, child, n);
}