One additional process will be created each time fork is called.
The first time fork called, the parent process P creates subprocess SP1. After fork, the parent process calls fork again (skips if ), creating the SP2 subprocess.
SP1, after calling fork fork inside if , creates a subprocess of SSP1. Then SP1 spawns a stream. SP1 leaves if . and calls fork again, creating a subprocess of SSP2.
SSP1 spawns a stream. SSP1 exits if and calls fork , creating a sub-sub-SSSP process.
So, the processes are created: processes SP1, SP2, SSP1, SSP2, SSSP = 5. If you consider the initial process P, there are 6 processes.
Only SP1 and SSP1 spawn threads, so 2 threads are created. If you count all the main threads of all processes, there are 7 or 8 threads, depending on whether you think the source process is P.
Illustration of the processes and threads being created correlates with the code.
P pid t pid; | pid = fork(); +------SP1 if (pid == 0) { | | fork(); | +---------------SSP1 thread create(...); | |-SP1 thread |-SSP1 thread } | | | fork(); +-SP2 +-SSP2 +-SSSP | | | | | |
source share