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
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.