D3fman
D3fman

Reputation: 85

fork(), problems with multiple children

I edited a little bit :

for ( ii = 0; ii < nbEnfants; ++ii) {
    switch (fork()){
        case -1 : {
                    printf("\n\nSoucis avec fork() !!! \n\n");
                    exit(0);
                    };

        case 0 : {
                    EEcrireMp(ii);
                    }break;
        default : {
                    tabPidEnfants[ii] = p;
                    usleep(50000);
                    ELireMp(nbSect, nbEnfants,tabPidEnfants);
                    };
    }
}

My problem : i get to many child, like a bomb of children spawning. How can i stop those child ? the break should stop it no ?

Thanks

Upvotes: 0

Views: 583

Answers (1)

Mats Petersson
Mats Petersson

Reputation: 129524

So, when you fork a process, the new process is an identical copy of the parent, so when your child continues from the if ((pid = fork()) == 0) ..., it will continue out into the for-loop and create more children.

The child should use exit(0) when it's finished (or at least NOT continue the fork-loop - you could use break; to exit the loop for example. Eventually, the child process should exit however.

In the OTHER side, if you want to make sure this child is FINISHED before creating the next fork, you should use waitpid() or some other variant of wait. Of course, these will wait for the forked process to exit, so if the forked process doesn't exit, that's not going to work. But you need to have a strategy for how you deal with each process. If you want to have 20 forked processes running at once, then you will probably need to store your pid in an array, so you can track the processes later. One way or another, your main process should track and ensure the processes are finished before it finishes itself.

Upvotes: 3

Related Questions