Consider the following segment of codes related to process creation. How many…
2017
Consider the following segment of codes related to process creation. How many times the message “child process created” will be printed?
#include <stdio.h>
void main()
{
fork();
fork();
fork();
printf("child process created");
}
Answer: C. 8 — fork() splits the process that calls it into two independent processes — the original process and a new copy — and both processes resume execution from the…
- A.
9
- B.
7
- C.
8
- D.
3
Attempted by 559 students.
Show answer & explanation
Correct answer: C
fork() splits the process that calls it into two independent processes — the original process and a new copy — and both processes resume execution from the very next statement onward. If a program executes fork() n times in succession with no condition on its return value, every process alive at each call also executes that same call, so the total number of processes doubles at each of the n calls, giving 2n processes overall. Every one of those processes then independently executes any statement that follows — including a printf() — exactly once.
Before the first
fork(): exactly 1 process is running.First
fork()executes: the 1 running process becomes 2 processes — the original process and a new copy.Second
fork()executes: each of the 2 currently running processes callsfork()independently, so 2 processes become 4.Third
fork()executes: each of the 4 currently running processes callsfork()independently, so 4 processes become 8.All 8 processes then reach the
printf("child process created")statement — it has no condition on thefork()return value, so every one of the 8 processes executes it exactly once.
As an independent check: counting only the processes newly spawned by the three fork() calls gives 23 − 1 = 7 new child processes; adding back the single original process, which also survives and reaches the printf() statement, gives 7 + 1 = 8 processes in total — the same count reached by direct doubling above.
Therefore, the message “child process created” is printed 8 times in total.
Explore the full course: Iocl Engineers Officers Grade A Paper 2