Aptitude Overflow
+10 votes
885 views

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. 2n - 1
  4. 3n - 1
asked in Operating System by (21.2k points) 125 160 160 | 885 views

3 Answers

+19 votes
Best answer

Option C.

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

answered by (265 points)
edited by
+4 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.

answered by (5.7k points)
+3 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.

 

 

answered by (3.1k points)
edited by
when n=1 child= 4?? how??

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.

Alright, Thanks.

But try to understand the above approach.

hmmm got it ...

Related questions

2,706 questions
981 answers
387 comments
31,354 users