FelgPires
FelgPires

Reputation: 11

Tree Fork() Recursion

I'm trying to run the tree below using a recursive function of Fork ().However, I can only generate the first 3 children, for the rest of the tree, I lose the correct reference. Tree Picture

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);
}

Upvotes: 1

Views: 208

Answers (1)

cjkeilig
cjkeilig

Reputation: 101

It looks like your recursion termination is exiting the program prematurely. With recursion, I usually use 'return'.

Upvotes: 1

Related Questions