How many processes and threads will be created?

I have this code and am trying to figure out how many processes and threads will be created from this:

pid t pid; pid = fork(); if (pid == 0) { /* child process */ fork(); thread create( . . .); } fork(); 

I think it creates 2 threads from the fork inside the if loop. and 8 processes? But I'm not sure if this is true

+6
source share
3 answers

Actually, there should be 8 threads and 6 processes.

Here are diagrams to make it clear:

 1) after first fork(): |------------------- child of p0 [p1] ---|------------------- parent [p0] 2) after second fork(): |--------------- child of p1 [p2] |---|--------------- [p1] ---|------------------- [p0] 3) after pthread_create(): ----------- thread 1 of p2 [p2t1] |---/----------- thread 0 of p2 [p2t0] | ----------- thread 1 of p1 [p1t1] |---|---/----------- thread 0 of p1 [p1t0] ---|------------------- [p0] 4) after third fork(): |------------ child of p2 [p5] | ------ [p2t1] |-|-----/------ [p2t0] | |---------- child of p1 [p4] | | ------ [p1t1] |---|---|---/------ [p1t0] | |------------ child of p0 [p3] ---|-----|------------ [p0] 

Important: Remember that calling fork (2) only clones the thread that executed it, so process 4 [p4] has only one thread (the same applies to process 5 [p5]).

+10
source

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 | | | | | | 
+7
source

shouldn't there be 2 threads and 6 processes?

 M | ↘ MA | |↘ MA* B* | | | | ↘ ||↘ MCADBE 

as I use * to represent the stream.

0
source

All Articles