Flama
Flama

Reputation: 868

How does fork() stop creating children?

Can anyone explain me how this works?

if I have in my code something like

int pids[N];
for(int i = 0; i < N; i++){
    pids[i] = fork();
    if(pids[i]==0){
        //do something
        break;
    }
}

Wouldn't I be creating N children and then in each child N children again and end up in a loop?

Upvotes: 0

Views: 363

Answers (2)

melpomene
melpomene

Reputation: 85887

Wouldn't I be creating N children

Yes.

and then in each child N children again

No, why? Every child process executes break; and leaves the loop. No further processes are created.

and end up in a loop?

Even if you didn't have that break; in there, every child would just execute the rest of the for loop. It wouldn't restart from i = 0. That means in every iteration the number of processes would double, so you'd end up with 2^N processes total. But with that break; it's just plain N.

Upvotes: 4

From http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/fork/create.html (emphasis mine):

After a new child process is created, both processes will execute the next instruction following the fork() system call.

So, fork() creates a child, and the child does not start from the beginning of the loop: it starts from the instruction after the call to fork, that is, from if(pids[i]==0){, which for the child is true. Then it will do something, and then break. Break means that it exits the for loop, thus the child does not create any more processes.

So, the father creates N children, whereas each child does the work and breaks from the loop without creating any more children.

Upvotes: 5

Related Questions