in Operating System edited by
16,908 views
29 votes
29 votes

A process executes the following code

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

The total number of child processes created is

  1. $n$
  2. $2^n-1$
  3. $2^n$
  4. $2^{n+1} - 1$
in Operating System edited by
16.9k views

3 Comments

Although a trivial approach one can eliminate option C & D, right away by putting $n=1$
0
0
Sadly you will not find such questions now in GATE.
0
0
less possibility
0
0

3 Answers

37 votes
37 votes
Best answer

Each fork() creates a child which start executing from that point onward. So, number of child processes created will be $2^n - 1$.

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

Reference: https://gateoverflow.in/3707/gate2004-it_64

edited by
by

4 Comments

please elaborate.
0
0

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

0
0

@Arjun sir there is only one small mistake as for loop runs from 0 to n-1 

so 1-2-4-8 – – 2^n-1  so answer will be 2^n-1

 

0
0
3 votes
3 votes

in this solution I have explained more deeply what exactly happening, pls upvote if u like the soln :)

1 vote
1 vote
         F0       // There will be 1 child process created by first fork

      /     \

    F1      F1    // There will be 2 child processes created by second fork

   /  \    /  \

 F2   F2  F2   F2  // There will be 4 child processes created by third fork

/ \   / \ / \  / \

 ...............   // and so on

If we sum all levels of above tree for i = 0 to n-1, we get 2n - 1. So there will be 2n – 1 child processes. On the other hand, the total number of process created are (number of child processes)+1.

 

Note:The maximum number of process is 2n and may vary due to fork failures.Also see this post for more details.

1 comment

int main(){

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

if(fork()==0)

printf(“os”)

}

printf(“gate”);

}

  • how many times os and gate printed?
0
0
Answer:

Related questions