in Operating System
8,536 views
35 votes
35 votes

A process executes the following segment of code :

for(i = 1; i <= n; i++)
    fork ();


The number of new processes created is

  1. $n$
  2. $((n(n + 1))/2)$
  3. $2^n - 1$
  4. $3^n - 1$
in Operating System
8.5k views

6 Answers

36 votes
36 votes
Best answer

Option (C).

At each fork, the number of processes doubles like from $1 - 2 - 4 - 8 ... 2^n$. Of these except $1$, all are child processes.

edited by
16 votes
16 votes
  fork ();    // Line 1
  fork ();   // Line 2
  fork ();   // Line 3
.....till n

       L1       // There will be 1 child process created by line 1
    /     \
  L2      L2    // There will be 2 child processes created by line 2
 /  \    /  \
L3  L3  L3  L3  // There will be 4 child processes created by line 3
........

We can also use direct formula to get the number of child processes.

With n fork statements, there are always 2n – 1 child process.

7 votes
7 votes

The process created are always found in the leaf of the tree.

So for n iteration 2^n-1 new process created.

4 votes
4 votes

Answer : Option (C)

Let's take a simple example.

For convenience and simplicity let's take the code as,

for(i = 1; i < = n; i++) 
    { 
      fork (); 
    } 
Print("Hello");

Now trace the program on paper manually.

You will find that For i=1 , 
Hello will be Printed 4 times.

For i=2 , 
Hello will be Printed 2 times.

For i=3 , 
Hello will be Printed 1 time.

After Loop Gets Terminated 

Finally parent Process(Original One) will Print Hello.

That is 8 times Hello will be printed, in which only last one belongs to the Parent Process. 

So, total Child Processes = 8-1(Parent)= 7 = 23 - 1.

In general,

total Child Processes = 2n-1(Parent) = 2n - 1.

 
edited by

4 Comments

Alright, Thanks.

But try to understand the above approach.

0
0
hmmm got it ...
0
0
where you mentioned that n=3?? @jason_gate
0
0
Answer:

Related questions