6,970 views
3 votes
3 votes

 Consider the following code segment:

pid_t pid;
pid = fork();

if (pid == 0) { /* child process */

fork();

thread create( . . .);

} fork();

a. How many unique processes are created?

b. How many unique threads are created? 

3 Answers

Best answer
1 votes
1 votes

1st --> 1 child process
       + 1 parent process


2nd --> 1 child process( + 2 threads) + 1 child1 process( + 2 threads)
        + 1 parent process

3rd --> 1 child process( + 2 threads) + 1 child2 process( + 2 threads)
        + 1 child1 process( + 2 threads) + 1 child3 process( + 2 threads)
        + 1 parent process + 1 child4 process

a) 6 processes (Total)

b) 8 threads

explaination for 3rd fork:-
 fork creates exact same process as parent so...when child calls 3rd fork it has two threads...so fork will clone the child process which is child2 here child2 will also have 2 threads same goes with child1

selected by
0 votes
0 votes

I think 6 processes in total

and 8 threads would be created shown in image,

circle is process, and 2 sections in falf circle means 2 threads ( main thread of execution + one  )

as when child process is created it totally replicates its parent ( includind parents threads )

, but threds run on same code segent so, fork would be called only by one of the threads not both

edited by
0 votes
0 votes

Toal 6 process created

1.pid = fork(); // here 2 process will created.

Now, in those processes,1 process pid contains value 0 , that is called child process. and other one process contains non zero value, i.e. parent process.

2.if (pid == 0)

Now, from child process another process called, which also creates 2 process, 1 child and another parent.

Now, as fork() is a cloning method, it only call another fork() from last processes.

Now, in (1) only parent process is left which can create 2 processes, and in (2) both parent and child can create 2+2=4 processes.

So, total 6 processes can be created.

10 unique threads will be created

edited by

Related questions

1 votes
1 votes
1 answer
3
Mukesh Bhandari 1 asked Jan 19, 2018
297 views
Is thread share pc
2 votes
2 votes
1 answer
4
set2018 asked Oct 27, 2017
216 views
A thread running in critical section may get context switch .Correct or not?