fork is not "recursive" in the traditional meaning of recursion. A call to
fork() duplicates the current process so it "returns twice". For the child process, the return value is 0, and for the parent the return value is the child PID.
fork() does not restart
main - that would be more like
fork followed by
Your program works like this. First let's insert some line numbers:
1: #include <stdio.h>
2: #include <stdlib.h>
3: #include <string.h>
5: int main(int argc, char *argv)
13: return 0;
Let's say you start your program and it gets a PID of P.
After line 7, the call to
fork results in two separate processes, both at line 8, one with PID P (the original) and one with a pid of C1 (the new child).
P runs line 8 and spawns a new child, with PID C2. Both P and C2 are at line 9 now. Meanwhile, C1 runs line 8 and spawns a new child, CC1. Both CC1 and C1 are at line 9 as well. (Not entirely relevant, but the order in which the above two sentences occur is indeterminate. They could happen simultaneously on multi-processor systems.)
There are now a total of 4 processes: P, C1, C2, and CC1. As you can see, each successive
fork doubles the amount of processes. Since there are 3
fork calls, you end up with 23 or 8 processes. The genealogy looks something like:
P (initial process, started by you)
+-- C1 (created on line 7)
| +-- CC1 (created on line 8)
| | +-- CCC1 (created on line 9)
| +-- CC2 (created on line 9)
+-- C2 (created on line 8)
| +-- CC3 (created on line 9)
+-- C3 (created on line 9)
Each process is created by its parent in the tree.