I'm trying to trace this program. I see that it outputs 4 times when I run it, but I don't understand why.
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
if (fork() == 0)
fork();
else
{
fork();
fork();
printf("%d\n", getpid());
}
}
To my knowledge, the if/else forks my program, then if we're in the child, it forks again. If we're in the parent, it runs the code in the else block. I get confused when I try to trace after this point, though.
Once the else statement forks again, aren't we in another child?
When do the children stop being spawned?
After getting it explained for me, I understand it now.
The first fork will spawn a child (let's call it c1):
if (fork() == 0)
The return value of fork is 0 when you're in the child. So, c1 will execute the if statement block:
fork();
The child created here, c2 (as well as c1) will both die, as they aren't going to execute the else block.
Meanwhile, the parent process will execute the else block.
fork();
This creates another child of the original parent process (c3). c3 will execute the next fork in the else block.
fork();
Now, we'll have c4, too.
Meanwhile, the original parent process will still have a fork that hasn't run. This creates the final child process, c5.
At the end of the run, there will be 4 prints: The original parent process, c3, c4, and c5.