A process executes the following segment of code : for(i = 1; i < = n; i++)…
2004
A process executes the following segment of code :
for(i = 1; i < = n; i++)
fork (); The number of new processes created is
- A.
n
- B.
((n(n + 1))/2)
- C.
2n - 1
- D.
3n - 1
Attempted by 260 students.
Show answer & explanation
Correct answer: C
Answer: The number of new processes created is 2^n - 1.
Start with one original process before the loop begins.
Each fork() call duplicates every existing process, so if there are X processes before a fork, there are 2·X after it.
After k iterations (k fork calls) the total number of processes is 2^k. Therefore after n iterations the total is 2^n, and the number of new processes created equals total minus the original = 2^n - 1.
Quick examples:
n = 1: total processes = 2^1 = 2, new = 1
n = 2: total processes = 2^2 = 4, new = 3
n = 3: total processes = 2^3 = 8, new = 7
A video solution is available for this question — log in and enroll to watch it.