Operating SystemUnit 211 min read
Process Management: States, Control, Synchronization & Deadlocks
Unit 2 of Operating System explores process creation, states (ready, running, waiting), process control blocks (PCBs), inter-process communication (IPC), synchronization (race conditions, semaphores, monitors), and deadlocks (conditions, prevention, detection). It covers how processes interact with CPU, memory, and I/O
TAKEAWAYS:
- A process is an executing program with its own PCB (Process Control Block) tracking state, registers, and resources.
- Processes cycle through five states (new → ready → running → waiting → terminated) managed by the OS scheduler.
- Race conditions and critical sections require synchronization (semaphores, monitors) to avoid corruption.
- Deadlocks occur when four conditions (mutual exclusion, hold-and-wait, no preemption, circular wait) align; prevention or detection algorithms (e.g., Banker’s) resolve them.
- IPC mechanisms (shared memory, message passing) enable processes to communicate safely.
- Process creation (fork, exec) and termination (exit, abort) are core OS functions with parent-child relationships.
1. What is a Process?
A process is a program in execution, with its own:
- Program counter (PC): Tracks next instruction.
- Registers: CPU state (e.g.,
R1,SP). - Memory space: Code, data, stack, heap.
- I/O resources: Files, devices.
Process vs. Program
| Process | Program |
|---|---|
| Dynamic, executing entity | Static, stored file |
| Requires resources (CPU, memory) | Passive, needs OS to run |
| Has a Process Control Block (PCB) | No PCB; just instructions |
2. Process States and Transitions
Processes transition between five states:
- New: Process created (e.g.,
fork()in Linux). - Ready: Waiting for CPU (in ready queue).
- Running: Executing on CPU.
- Waiting/Blocked: Awaiting I/O or event (e.g.,
read()from disk). - Terminated: Execution complete (exit code stored in PCB).
stateDiagram-v2
[*] --> New: Process Creation
New --> Ready: Admitted to Ready Queue
Ready --> Running: CPU Allocation
Running --> Waiting: I/O Request
Waiting --> Ready: I/O Complete
Running --> Ready: Time Slice Expires
Running --> Terminated: Exit/Abort
Terminated --> [*]Real-World Example: eSewa Payment Process When you pay a bill via eSewa:
- New: Your payment request is created.
- Ready: Waits in the bank’s transaction queue.
- Running: Bank processes the deduction.
- Waiting: Awaits SMS confirmation from Ncell/NTC.
- Terminated: Payment completes (or fails).
3. Process Control Block (PCB)
The PCB is the process descriptor stored in memory. Key fields:
- Process ID (PID): Unique identifier (e.g.,
P1,P2). - Process State: Current state (ready/running/waiting).
- Program Counter (PC): Next instruction address.
- CPU Registers: Saved state when process is preempted.
- CPU Scheduling Info: Priority, remaining time.
- Memory Limits: Base/limit registers for memory protection.
- I/O State: Open files, device status.
- Accounting Info: CPU time used, billing.
4. Process Scheduling
The short-term scheduler (CPU scheduler) selects a process from the ready queue to run. Criteria:
- CPU Utilization: Keep CPU busy (e.g., 90%).
- Throughput: Processes completed per unit time.
- Turnaround Time: Time from submission to completion.
- Waiting Time: Time spent in ready queue.
- Response Time: Time from request to first response.
Worked Example: FCFS Scheduling
Given processes with arrival time (AT) and burst time (BT):
| Process | AT | BT |
|---|---|---|
| P1 | 0 | 6 |
| P2 | 2 | 4 |
| P3 | 4 | 3 |
Gantt Chart:
P1 (0-6) | P2 (6-10) | P3 (10-13)
- Turnaround Time (TAT) = Completion Time – Arrival Time
- P1: 6 – 0 = 6
- P2: 10 – 2 = 8
- P3: 13 – 4 = 9
- Average TAT = (6 + 8 + 9) / 3 = 7.67
- Waiting Time (WT) = TAT – BT
- P1: 6 – 6 = 0
- P2: 8 – 4 = 4
- P3: 9 – 3 = 6
- Average WT = (0 + 4 + 6) / 3 = 3.33
Exam Tip: Always draw the Gantt chart for scheduling questions!
5. Inter-Process Communication (IPC)
Processes communicate via:
- Shared Memory: Fast, but requires synchronization (e.g., two processes reading/writing a shared buffer).
- Message Passing: Slower but safer (e.g.,
send()/receive()in Linux).- Direct: Sender knows receiver’s PID.
- Indirect: Uses a mailbox (e.g., WhatsApp messages via servers).
Real-World Example: Pathao Driver-Passenger Matching
- Shared Memory: Not used (security risk).
- Message Passing:
- Passenger sends request to Pathao server (message:
"Need ride from X to Y"). - Server matches with nearest driver (message:
"Driver D1 assigned"). - Driver accepts (message:
"Accepted"), and both get real-time updates.
- Passenger sends request to Pathao server (message:
6. Synchronization: Race Conditions and Critical Sections
Problem: Two processes accessing shared data concurrently can corrupt it. Example: Two bank tellers updating the same account balance:
// Process P1
balance = balance - 100; // Read, subtract, write
// Process P2
balance = balance - 200; // Overwrites P1's changes!
Solution: Critical Section Problem requires:
- Mutual Exclusion: Only one process in CS at a time.
- Progress: No process waits indefinitely.
- Bounded Waiting: No starvation.
Tools for Synchronization:
| Method | Description | Example Use Case |
|---|---|---|
| Semaphores | Integer variable + wait()/signal() |
Printer spooling (one job at a time) |
| Monitors | High-level construct (e.g., Java synchronized) |
Database transactions |
| Mutex Locks | Binary semaphore (lock/unlock) | Thread-safe queues |
Worked Example: Dining Philosophers (Semaphore Solution)
stateDiagram-v2
[*] --> Thinking: Philosopher thinks
Thinking --> Hungry: Picks up fork
Hungry --> Wait: Tests semaphore
Wait --> Eat: If fork available
Eat --> PutDown: Releases fork
PutDown --> ThinkingReal-World Example: Kathmandu Traffic Lights
- Race Condition: Two cars at an intersection without synchronization → collision.
- Solution: Traffic lights act as semaphores:
semaphore = 0(red light): No cars allowed.semaphore = 1(green light): One direction proceeds.
7. Deadlocks: Conditions and Prevention
A deadlock occurs when processes are blocked forever, waiting for resources held by each other.
Four Necessary Conditions:
- Mutual Exclusion: Only one process can use a resource at a time (e.g., printer).
- Hold and Wait: Process holds a resource while waiting for another.
- No Preemption: Resources cannot be forcibly taken (e.g., CPU time slices can be preempted, but a printer job cannot).
- Circular Wait: A circular chain of processes waiting for each other (e.g., P1 → R1 → P2 → R2 → P1).
Example Scenario:
| Process | Allocated | Requested | Available |
|---|---|---|---|
| P1 | R1 | R2 | R3 |
| P2 | R2 | R1 |
Graph Representation:
graph TD
P1["P1"] -->|"Holds"| R1["R1"]
P1 -->|"Waits"| R2["R2"]
P2["P2"] -->|"Holds"| R2
P2 -->|"Waits"| R1Prevention Strategies:
| Method | How It Works | Example |
|---|---|---|
| Resource Ordering | Assign a global order to resources. | Always request R1 before R2. |
| Timeouts | Release resources if not acquired in T time. |
eSewa cancels payment after 5 mins if bank hangs. |
| Deadlock Avoidance | Use algorithms (e.g., Banker’s) to ensure safety. | Ncell reserves bandwidth before call starts. |
Banker’s Algorithm Worked Example: Given:
- Available: [1, 0, 2]
- Max Need:
Process A B C P0 7 5 3 P1 3 2 2 P2 9 0 2 P3 2 2 2 - Allocation:
Process A B C P0 0 1 2 P1 1 0 0 P2 1 0 2 P3 0 1 0
Step 1: Calculate Need = Max – Allocation. Step 2: Check if Available ≥ Need[P0]? No → Skip P0. Step 3: P1’s Need = [2, 2, 2] ≤ Available? No. Step 4: P3’s Need = [2, 1, 2] ≤ Available? No. Step 5: P2’s Need = [8, 0, 0] ≤ Available? No. Conclusion: No safe sequence → Deadlock possible.
8. Process Creation and Termination
Process Creation:
- Parent Process: Creates child via
fork()(copy of parent) orexec()(load new program). - Child Process: Inherits parent’s resources (e.g., file descriptors) unless modified.
Example:
# Parent (PID 1234) creates child
fork(); // Child gets PID 5678
exec("ls"); // Child replaces itself with 'ls' command
Termination:
- Normal Exit: Process calls
exit()(returns status to parent). - Abnormal Exit: Killed by
kill()or OS (e.g., segmentation fault). - Zombie Process: Terminated but not reaped by parent (use
wait()to clean up).
Real-World Example: WhatsApp Message Delivery
- Parent: Your phone (PID 1000).
- Child: Message delivery process (PID 1001) created when you send a message.
- If delivery fails (e.g., no internet), child terminates abnormally.
- Parent (WhatsApp app) reaps the child to free resources.
In the Real World
eSewa Payments
- Process States: Your payment request moves from
New(created) →Ready(queued) →Running(processing) →Terminated(completed or failed). - Synchronization: Bank uses semaphores to ensure only one transaction modifies your account at a time.
- Deadlock Prevention: If eSewa hangs, it uses timeouts to cancel pending transactions.
- Process States: Your payment request moves from
Pathao Ride Allocation
- IPC: Driver and passenger processes communicate via message passing (server acts as mailbox).
- Scheduling: Pathao’s algorithm (like SJF) assigns the nearest available driver to minimize waiting time.
NTC Electricity Billing System
- Processes: Meter reading → Billing → Payment processing.
- Deadlock Risk: If two processes lock the same customer record, the system uses resource ordering (e.g., always lock by customer ID ascending).
Exam Tip
- Process States: Always draw the state transition diagram (5 states + arrows). Examiners love this!
- Scheduling: For Gantt charts, label time intervals clearly and calculate TAT/WT step-by-step.
- Deadlocks:
- Define the 4 conditions and give an example (e.g., two processes waiting for each other’s printers).
- For Banker’s Algorithm, show the Need matrix and explain why a sequence is safe/unsafe.
- Synchronization:
- For race conditions, write a code snippet showing the problem (e.g., two processes incrementing a counter).
- For semaphores, describe
wait()andsignal()and give a real-world analogy (e.g., traffic lights).
- IPC: Compare shared memory vs. message passing in a table (speed vs. safety).
Common Pitfalls:
- Forgetting to include arrival times in scheduling questions.
- Not checking all processes in Banker’s Algorithm (missing one can lead to wrong conclusions).
- Drawing a deadlock graph incorrectly (e.g., missing arrows for "waiting for").
Based on the TU BCA syllabus for Operating System (CACS251), unit 2.
Discussion
Loading…