I have this code
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(){
int pid = fork();
fork();
if (pid == 0)
{
fork();
fork();
}
printf("process ID: %dn", getpid());
return 0;
}
I need to know why it’s printed 10 times, how we get exactly 10 processes.
3
You start with one process.
After the first fork, you have two processes, one with a zero pid
variable and one with a nonzero pid
variable.
Both processes then fork again, so you have four processes, two with a zero pid
variable and two with a nonzero pid
variable.
At this point, the two processes with the nonzero pid
variable skip the if
code and fall through to the printf
call, then exit.
But the other two processes, with the zero pid
variable, both fork again, resulting in four processes with a zero pid
variable, then those four processes fork again, resulting in eight processes with a zero pid
variable. Those eight processes then proceed to the printf
call, then exit.
So you end up with a total of ten processes. Two of them have a nonzero pid
variable and the other eight have a zero pid
variable.
2
While the answer from Tom is correct, I will add context for why 7 is not correct.
You (like I initially thought) incorrectly assumed the main process is the only process with pid = 0. The following code is what we thought we were doing:
main.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(){
int pid = getpid(); // get pid of main process
fork();
fork();
if (getpid() == pid) // only main process makes this true
{
fork();
fork();
}
printf("process ID: %dn", getpid());
return 0;
}
Compiling and running gives the desired 7 pids.
gcc main.c -o out
./out
stdout
process ID: 81711
process ID: 81710
process ID: 81709
process ID: 81713
process ID: 81714
process ID: 81712
process ID: 81715