How many times will "Bye" be displayed if the following program is executed?…

2019

How many times will "Bye" be displayed if the following program is executed?

#include<stdio.h>

int main()
{
    printf("Hello\n");
    fork();
    printf("World\n");
    fork();
    printf("Bye\n");
    fork();
}

Answer: B. 4ConceptA fork() call duplicates the calling process: after it returns, a parent and a child both continue from the very next statement. Every fork() therefore…

  1. A.

    2

  2. B.

    4

  3. C.

    6

  4. D.

    8

Attempted by 33 students.

Show answer & explanation

Correct answer: B

Concept

A fork() call duplicates the calling process: after it returns, a parent and a child both continue from the very next statement. Every fork() therefore doubles the number of processes that run the code following it, so n successive fork() calls executed by every process leave 2n processes alive. A statement placed after k fork() calls is executed once by each of the 2k processes alive at that point, and so produces 2k lines of output.

Application to this program

  1. The program begins as a single process, and that one process executes printf("Hello\n"), so "Hello" is displayed once.

  2. The first fork() runs, taking the process count from 1 to 2. Both processes go on to execute printf("World\n"), so "World" is displayed twice.

  3. The second fork() runs and each of those 2 processes splits, giving 4 processes that all reach printf("Bye\n").

  4. Each of those 4 processes executes printf("Bye\n") exactly once, so "Bye" is displayed 4 times.

  5. The third fork() executes only after "Bye" has been printed. It takes the process count from 4 to 8, but no output statement follows it, so it cannot add to the "Bye" count.

Cross-check

Apply 2k, where k is the number of fork() calls a statement follows:

Statement

fork() calls before it

Times displayed

printf("Hello\n")

0

1

printf("World\n")

1

2

printf("Bye\n")

2

4

Because each printf ends with \n and standard output to a terminal is line-buffered, every line is flushed before the next fork() runs, so text that has already been printed is never duplicated by a later fork(). With k = 2 for printf("Bye\n"), the count is 22 = 4.

Explore the full course: Niacl Ao It Specialist

Loading lesson…