8,731 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. $2^n - 1$
4. $3^n - 1$

Total count print is 8 (one for the main function)

So, the answer is $2^{3} -1 = 7$

But why static variable count is printing only 1 ????

@Deepak Poonia @Arjun Sir

@Abhrajyoti00

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.

by
  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.

by

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

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

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 ...
where you mentioned that n=3?? @jason_gate