The following C program is executed on a Unix/Linux system: #include…

20192024

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 ________.

Attempted by 151 students.

Show answer & explanation

Correct answer: 31

Key idea: each fork() call doubles the number of processes that exist at that point.

  • The loop runs for i = 0..9 (10 iterations), and fork() is called when i%2 == 0, i.e., for i = 0, 2, 4, 6, 8 — that's 5 fork calls.

  • Each fork doubles the number of processes, so after 5 forks the total number of processes is 2^5 = 32.

  • The number of child processes created is the total minus the original parent: 32 − 1 = 31.

Answer: 31 child processes.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir