Sub topic 18
Worked GATE-Style Problems: Fork Counting and Gantt Charts
This chapter assumes basic C, process creation with fork, queues, and arithmetic with time intervals. Use a process tree for fork questions and a timeline table for scheduling questions.
Counting Processes After `fork`
fork() creates one new process. After it returns, both the parent and child continue from the next statement. Therefore, a later fork() runs once in every process that already exists.
#include <stdio.h>
#include <unistd.h>
int main(void) {
fork();
fork();
fork();
printf("hello\n");
return 0;
}After the first call, there are 2 processes. After the second, there are 4. After the third, there are 8. Each process reaches printf, so the output contains hello 8 times.
For n unconditional, successful fork() calls:
- Number of final processes:
2^n - Number of new child processes:
2^n - 1 - Executions of a later statement:
2^n
Do not count printed lines as process count when the print statement is before a fork. Also check conditions. For example, a fork() inside if (fork() == 0) is reached only by the child created by the first call.
Building a Scheduling Timeline
For scheduling problems, record arrival time, burst time, first execution, and completion time. The following example uses Round Robin with quantum 2. All processes arrive at time 0.
| Process | Burst time | Execution slices | Completion |
|---|---|---|---|
| P1 | 5 | 0–2, 6–8, 12–13 | 13 |
| P2 | 3 | 2–4, 8–9 | 9 |
| P3 | 8 | 4–6, 9–11, 13–15, 15–16 | 16 |
The ready queue begins as P1, P2, P3. A process that still has work goes to the back of the queue after its quantum.
For this example, response time is first start minus arrival time. Turnaround time is completion minus arrival. Waiting time is turnaround minus burst time.
| Process | Response | Turnaround | Waiting |
|---|---|---|---|
| P1 | 0 | 13 | 8 |
| P2 | 2 | 9 | 6 |
| P3 | 4 | 16 | 8 |
The timeline must respect arrivals. If no process has arrived, insert idle time. For SRTF, recalculate the remaining burst whenever a new process arrives. For priority scheduling, state clearly whether a smaller or larger number means higher priority.
Exercise
Three unconditional fork calls are followed by one print statement. How many processes execute the print, and how many child processes are created?
Show answer
Eight processes execute the print. Seven are children created in total.