Assuming that the system call fork() never fails, consider the following C…

2020

Assuming that the system call fork() never fails, consider the following C program 𝑃1 and 𝑃2 executed on a UNIX/Linux system:

/* P1 */

int main() {

fork();

fork();

fork();

printf("Happy\n");

}

/* P2 */

int main() {

fork();

printf("Happy\n");

fork();

printf("Happy\n");

fork();

printf("Happy\n");

}

Statement 𝐼: 𝑃1 displays “Happy” 8 times

Statement 𝐼𝐼: 𝑃2 displays “Happy” 12 times

In the light of the above statements, choose the correct answer from the options given below

  1. A.

    Both Statement 𝐼 and Statement 𝐼𝐼 are true

  2. B.

    Both Statement 𝐼 and Statement 𝐼𝐼 are false

  3. C.

    Statement 𝐼 is correct but Statement 𝐼𝐼 is false

  4. D.

    Statement 𝐼 is incorrect but Statement 𝐼𝐼 is true

Attempted by 268 students.

Show answer & explanation

Correct answer: C

P1: Three fork calls occur before the single printf, so the number of processes is 2^3 = 8. Each process executes the printf once, so P1 prints "Happy" 8 times.

P2: The program follows the sequence: fork; printf; fork; printf; fork; printf. Count prints step by step.

  • Start with 1 process.

  • After the first fork there are 2 processes; the following printf is executed by both → 2 prints.

  • After the second fork there are 4 processes; the following printf is executed by all → 4 prints.

  • After the third fork there are 8 processes; the final printf is executed by all → 8 prints.

Total prints in P2 = 2 + 4 + 8 = 14.

Conclusion: Statement I is true (P1 prints 8 times). Statement II is false because P2 prints 14 times, not 12.

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

Explore the full course: Mppsc Assistant Professor