Project ForgeSign up free
Programming in C
Programming Fundamentals
GATE 2019
Hard

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

31

Explanation

fork() is called when i is even: i=0,2,4,6,8 — 5 fork points. Since every forked child also continues executing the SAME loop independently, each fork point doubles the total number of live processes. Starting from 1 process, after 5 sequential doubling points, total processes = 2^5 = 32. Total CHILDREN created = 32 − 1 (excluding the original parent) = 31.

Source: GATE CS 2019 (Set-2) (2019)

This question is part of a 15-day revision cycle — sign in and Project Forge will bring it back the day before you'd forget it.

Start revising free