Operating SystemUnit 211 min read
Process Management: States, PCB, Context Switching & IPC
Unit 2 of Operating System covers process creation, states (new → ready → running → waiting → terminated), Process Control Blocks (PCB), context switching overhead, inter-process communication (IPC), and real-world examples like eSewa’s transaction queues and Pathao’s ride-matching.
TAKEAWAYS:
- A process is an executing program with its own memory, registers, and state (e.g., a WhatsApp message thread running in the background).
- The PCB (Process Control Block) is the OS’s “passport” for each process, storing its ID, state, registers, and memory limits.
- Context switching (saving/restoring PCB) costs ~100–10,000 CPU cycles—critical for scheduling fairness (e.g., Daraz’s order-processing threads).
- IPC (shared memory, pipes, sockets) lets processes collaborate (e.g., Ncell’s billing system talks to the database via RPC).
- Zombie processes (terminated but lingering) and orphans (parent dead) are bugs—Linux kills them automatically.
- Exam focus: Trace process state diagrams, calculate context-switching overhead, and explain PCB fields.
1. What is a Process?
A process is a program in execution, with its own:
- Memory space (code, data, stack, heap).
- Process ID (PID) and parent PID (PPID).
- Execution state (running, ready, blocked).
- System resources (CPU time, file descriptors, I/O devices).
stateDiagram-v2
[*] --> New: Created but not admitted
New --> Ready: Admitted to ready queue
Ready --> Running: CPU allocated
Running --> Waiting: I/O or event block
Waiting --> Ready: Event completes
Running --> Terminated: Exit
Terminated --> [*]In the real world:
- eSewa: When you pay a bill, eSewa spawns a process to validate your transaction, another to deduct money from your bank, and a third to send the receipt. These processes communicate via IPC (shared memory or message queues).
- Pathao: A ride request creates a process to match you with a driver, another to track the driver’s location, and a third to handle payment. If the driver cancels, the matching process terminates and releases resources.
- Ncell’s Billing System: Each customer’s bill is processed by a separate thread (lightweight process). The OS schedules these threads using round-robin scheduling to ensure fair CPU time.
2. Process States and Transitions
Every process cycles through 5 states (shown above). Key transitions:
- New → Ready: Process is created (e.g.,
fork()in Linux) and added to the ready queue. - Ready → Running: CPU scheduler picks it (e.g., via SRTN for shortest remaining time).
- Running → Waiting: Process requests I/O (e.g., reading a file) or a signal (e.g.,
wait()for a child process). - Waiting → Ready: I/O completes or signal arrives (e.g., a file read finishes).
- Running → Terminated: Process exits (
exit()system call) or is killed (SIGKILL).
Worked Example: NTC’s Traffic Route Planner Assume NTC’s system runs 3 processes:
- Sensor Reader (P1): Collects traffic data every 5 seconds (I/O-bound).
- Route Optimizer (P2): Computes best paths (CPU-bound).
- Display Updater (P3): Updates the NTC website (I/O-bound).
Trace their states over 20 seconds:
| Time (s) | P1 (Sensor) | P2 (Optimizer) | P3 (Display) |
|---|---|---|---|
| 0–5 | Running → Waiting | Ready → Running | Ready |
| 5–10 | Waiting → Ready | Running → Waiting | Ready → Running |
| 10–15 | Running → Waiting | Waiting → Ready | Running → Waiting |
| 15–20 | Waiting → Ready | Ready → Running | Waiting → Ready |
Why? P1 blocks on I/O (sensor read), P2 yields CPU to P3 (round-robin), and P3 blocks while updating the web server.
3. Process Control Block (PCB)
The PCB is the OS’s “process descriptor,” storing:
classDiagram
class PCB {
+PID: int
+PPID: int
+State: {New, Ready, Running, Waiting, Terminated}
+Priority: int
+CPU Registers: [PC, SP, AX, BX, ...]
+CPU Scheduling Info: [Queue pointers, Timer]
+Memory Limits: [Base, Limit]
+I/O Status: [Open files, Devices]
+Accounting Info: [CPU time, Process owner]
}Key Fields Explained:
- PID/PPID: Unique identifiers (e.g.,
PID=1234,PPID=5678for a child process). - Registers: Saved when switching (e.g.,
PC= Program Counter,SP= Stack Pointer). - Memory Limits:
Base(start address),Limit(end address) to prevent overflow. - I/O Status: File descriptors (e.g.,
stdin=0,stdout=1) and device locks.
4. Context Switching
When the CPU switches from Process A → Process B, the OS:
- Saves A’s PCB (registers, state, memory pointers).
- Loads B’s PCB.
- Updates scheduling data (e.g., time slices in RR).
Overhead:
- Time: ~100–10,000 CPU cycles (modern OSes optimize this).
- Cost: High if frequent (e.g., 1000 switches/sec → 10% CPU waste).
Worked Example: Daraz’s Order Queue Daraz uses preemptive scheduling (e.g., SRTN) for order processing:
- Process A: Handles a ₹500 order (remaining time: 2ms).
- Process B: Handles a ₹50,000 order (remaining time: 20ms).
- Switch: At t=1ms, the scheduler preempts A for B (shorter remaining time).
- Overhead: Saving A’s registers + loading B’s PCB = 0.5ms wasted per switch.
Comparison Table: Scheduling Algorithms vs. Overhead
| Algorithm | Preemptive? | Overhead Impact | Best For |
|---|---|---|---|
| FCFS | No | Low (no preemption) | Batch systems |
| SJF/SRTN | Yes | High (frequent switches) | CPU-bound tasks |
| RR | Yes | Medium (fixed time slice) | Interactive systems |
| Priority | Yes/No | High (if aging is used) | Real-time systems |
5. Inter-Process Communication (IPC)
Processes need to share data or synchronize. Common methods:
| Method | Description | Example |
|---|---|---|
| Shared Memory | Processes map to the same memory region. | Ncell’s billing DB shared by 1000 threads. |
| Pipes | Unidirectional byte streams (FIFO). | grep "error" log.txt | sort. |
| Sockets | Network-based communication. | WhatsApp messages via TCP. |
| Message Queues | Kernel-managed buffers. | Pathao’s ride requests queue. |
| Semaphores | Synchronization (e.g., mutual exclusion). | Bank account transfers (lock balance). |
Worked Example: Bank Loan Processing (Semaphores) A bank’s loan system has:
- Process A: Validates customer credit.
- Process B: Approves the loan.
- Shared Data:
loan_amount(must not be modified simultaneously).
semaphore mutex = 1; // Binary semaphore for mutual exclusion
Process A:
wait(mutex); // Lock
loan_amount = 500000;
signal(mutex); // Unlock
Process B:
wait(mutex); // Lock
if (loan_amount > 1000000) reject();
signal(mutex); // Unlock
Problem: If both A and B try to wait(mutex) at the same time, deadlock occurs. Solution: Use semaphores or monitors.
6. Process Creation and Termination
Creation:
- Parent → Child:
fork()(Linux) orCreateProcess()(Windows). - Copy-on-Write (COW): Child shares parent’s memory until modified (saves RAM).
- Example:
# Parent process (PID=1234) child_pid = fork(); if (child_pid == 0) { // Child process (PID=5678) printf("Child running\n"); } else { // Parent continues printf("Parent running\n"); }
Termination:
- Normal Exit:
exit(0)(child) orreturn(main). - Abnormal Exit:
SIGKILL(forced),SIGSEGV(segmentation fault). - Zombie Processes: Terminated but not reaped by parent (e.g.,
ps aux | grep 'Z'). - Orphan Processes: Parent dies before child (adopted by
initin Linux).
7. Process Hierarchies and Orphans
- Tree Structure: Each process has a parent (except
init/PID 1). - Orphan Handling: If parent dies, child becomes orphan → adopted by
init(PID 1). - Zombie Handling: Parent must call
wait()orwaitpid()to clean up.
Example: Crash in a Web Server
- A web server (PID=1000) spawns 10 child processes to handle requests.
- If the server crashes (
SIGTERM), the children become orphans. - Linux’s
init(PID 1) reaps them to avoid zombies.
Exam Tip
- Diagrams are mandatory:
- Draw process state transitions (5 states + arrows).
- Sketch a PCB structure (label 5 key fields).
- Trace a context-switching timeline (show register saves/loads).
Worked examples:
- Given a page reference string, explain how it relates to process scheduling (e.g., "Process X’s page fault triggers a context switch").
- For IPC, always show a semaphore/mutex example with
wait()/signal().
Common pitfalls:
- Forgetting the 5th state: Terminated is often missed.
- PCB fields: Always include registers and memory limits.
- IPC vs. Threads: IPC is for processes; threads share memory (no need for semaphores).
Real-world links:
- eSewa: Use message queues for transaction logs.
- Pathao: Uses sockets for driver-passenger communication.
- Ncell: Round-robin scheduling for fair CPU time across billing threads.
Practice Question: *A system has 3 processes with the following details:
- P1: Arrival=0, Burst=6
- P2: Arrival=2, Burst=4
- P3: Arrival=4, Burst=2 Draw the Gantt chart and calculate the average waiting time using:
- FCFS
- SJF (non-preemptive)
- RR (quantum=2) Show the PCB state changes for P2 at t=2 and t=6.*
Based on the PU BE Computer (PU) syllabus for Operating System, unit 2.
Discussion
Loading…