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 i=0,1,2,…,9i = 0, 1, 2, \dots, 9:

for (i = 0; i < 10; i++)
    if (i % 2 == 0) fork();

The condition i % 2 == 0 evaluates to true for even values of ii:

i∈{0,2,4,6,8}i \in \{0, 2, 4, 6, 8\}

Thus, the fork() statement is executed exactly 55 times across the loop iterations.

Each fork() call duplicates all existing processes. Starting from 11 initial parent process:

  • After 1st fork: 21=22^1 = 2 processes
  • After 2nd fork: 22=42^2 = 4 processes
  • After 3rd fork: 23=82^3 = 8 processes
  • After 4th fork: 24=162^4 = 16 processes
  • After 5th fork: 25=322^5 = 32 processes

The total number of processes is 3232. Since 11 of them is the original parent process, the number of newly created child processes is:

Nchild=25−1=32−1=31N_{\text{child}} = 2^5 - 1 = 32 - 1 = 31
Final answer

31

Common trap

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.