in Operating System
6,587 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? 

in Operating System
6.6k views

1 comment

0
0

3 Answers

1 vote
1 vote
Best answer

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

4 Comments

those 4 will be duplicated by 3rd fork
0
0

@Lokesh  how 8? I am getting 10. correct me

0
0
threads are created inside the if condition ..
0
0
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

2 Comments

what about left side thread of main process?
0
0
fork function returns pid of child process created in parent process which is non 0

so top level process will not create any thread becase it will not go into

if block,

am I corret?, if not please correct me
0
0
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

1 comment

@srestha what about threads??
0
0

Related questions

1 vote
1 vote
1 answer
3
Mukesh Bhandari 1 asked in Operating System Jan 19, 2018
285 views
Mukesh Bhandari 1 asked in Operating System Jan 19, 2018
285 views