Question
The following C program is executed on a Unix/Linux system:
#include <unistd.h>
int main()
{
int i;
for (i = 0; i < 10; i++)
if (i % 2 == 0) fork();
return 0;
}
The total number of child processes created is ________.
Official answer and solution
- Official answer
- 31
- From
- Official GATE 2019 answer key
Solution
Trace the loop to count the number of fork() calls and determine the total child processes created.
The loop runs for :
for (i = 0; i < 10; i++)
if (i % 2 == 0) fork();
The condition i % 2 == 0 evaluates to true for even values of :
Thus, the fork() statement is executed exactly times across the loop iterations.
Each fork() call duplicates all existing processes. Starting from initial parent process:
- After 1st fork: processes
- After 2nd fork: processes
- After 3rd fork: processes
- After 4th fork: processes
- After 5th fork: processes
The total number of processes is . Since of them is the original parent process, the number of newly created child processes is:
31
Reporting 32 instead of 31 by forgetting to subtract the initial parent process.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2019 Computer Science and Information Technology (CS)
- Question
- 27 of 65, printed as CS Q.17
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.