AsterixKnut
AsterixKnut

Reputation: 77

Why does pid0 get printed twice with a value when forking?

I am struggling to understand why the variable pid0 gets printed twice with an actual id. As I have understood it, pid0 will be set to 0 for all of the forked processes after the first time.

This is my main function:

int main() {
  pid_t pid0, pid1, pid2;

  pid0 = fork();
  pid1 = fork();
  if (pid0 == 0) pid2 = fork();

  printf("pid0: %d, pid1: %d, pid2: %d\n", pid0, pid1, pid2);

  return 0;
}

And here is the output:

pid0: 3388, pid1: 3389, pid2: 32766
pid0: 3388, pid1: 0, pid2: 32766
pid0: 0, pid1: 3390, pid2: 3391
pid0: 0, pid1: 0, pid2: 3392
pid0: 0, pid1: 3390, pid2: 0
pid0: 0, pid1: 0, pid2: 0

Upvotes: 1

Views: 97

Answers (2)

Barmar
Barmar

Reputation: 781068

After you fork, both the parent and child continue executing the following code.

Let's call the original process P, and the child created with pid0 = fork() P-C1. Both of these processes then execute pid1 = fork(). We then have two more processes, which I'll call P-C2 and P-C1-C3.

Now all 4 processes execute the if statement. pid0 is 0 in both P-C1 and P-C1-C3, so they both execute pid2 = fork(). This creates processes P-C1-C4 and P-C1-C3-C5, and they inherit the zero value of pid0.

When all this is done, we have pid0 = 0 in processes P-C1, P-C1-C3, P-C1-C4, and P-C1-C3-C4. And pid0 != 0 in processes P and P-C2.

All 6 of these processes then print pid0.

Upvotes: 2

tadman
tadman

Reputation: 211600

Your first fork() creates a second process. Your second one runs on both processes and you've then got four processes. Two of these have pid0 set to 0, the other two do not.

The original forked process (pid0 === 0) and its clone will both call fork() again, so there's two more processes, for six total.

Of these four are part of the original fork() tree, and two are also in the secondary tree (pid1 == 0).

If you want only one parent process you must gate the second fork() and avoid doing it if pid0 is non-zero.

Notice the second line of your output has pid1: 0 which indicates it's a clone.

Upvotes: 2

Related Questions