Operating Systems

Unit 2: Process Management

From program to process โ€” master the lifecycle of processes, system calls that create & control them, and understand how your OS juggles thousands of tasks every second.

โฑ๏ธ Time to Complete: 6 hrs theory + 4 hrs lab  |  ๐Ÿ’ฐ Earning Potential: โ‚น5,000โ€“โ‚น15,000/month  |  ๐Ÿ“ 30 MCQs (Bloom's Mapped)

๐Ÿ’ผ Jobs this unlocks: Systems Engineer (โ‚น5โ€“8 LPA)  |  Linux Admin (โ‚น4โ€“7 LPA)  |  DevOps Intern (โ‚น15Kโ€“25K/month)

๐ŸŽฏ Interview Focus: TCS  |  Infosys  |  Amazon  |  Wipro  |  GATE CS

Section A

Opening Hook โ€” The Day India's Vaccine Portal Crashed

๐Ÿ’ฅ CoWIN Crashed โ€” 2 Crore Users, Zero Vaccines Booked

June 21, 2021. India opens COVID-19 vaccination for 18+ age group. At exactly 4:00 PM, 2 crore (20 million) users hit the CoWIN portal simultaneously. The servers didn't just slow down โ€” they froze completely. Pages returned blank. OTPs never arrived. Slots showed "available" but couldn't be booked.

What happened behind the scenes? Every user request spawned a process on the server. With 20 million near-simultaneous connections, the OS was drowning in processes. Each process needed a Process Control Block (PCB) โ€” consuming memory. The CPU tried to switch between thousands of processes โ€” context switching overhead consumed 90%+ of CPU time. The system spent more time switching between processes than actually executing them.

The fix? Engineers implemented process pooling, rate limiting (controlling how many new processes spawn), and queue-based scheduling โ€” all concepts you'll learn in this chapter.

Could YOU have prevented this crash? After this chapter โ€” yes, you absolutely could.

๐Ÿ‡ฎ๐Ÿ‡ณ CoWIN / NIC๐Ÿ‡ฎ๐Ÿ‡ณ Aadhaar / UIDAI๐Ÿ‡ฎ๐Ÿ‡ณ IRCTC๐Ÿ‡ฎ๐Ÿ‡ณ Amazon India๐Ÿ‡ฎ๐Ÿ‡ณ Flipkart๐Ÿ‡ฎ๐Ÿ‡ณ Paytm
Every time you open a tab in Chrome, a new process is created. Open 50 tabs? That's 50 separate processes, each with its own PCB, memory space, and CPU time slice. Chrome alone can consume 4 GB+ RAM because of this per-tab process architecture. This design choice is intentional โ€” if one tab crashes, others survive. That's process isolation in action!
Section B

Learning Outcomes โ€” Bloom's Taxonomy Mapped

Bloom's LevelLearning Outcome
๐Ÿ”ต RememberDefine a process, list all fields of the PCB, and name the 5 process states with valid transitions
๐Ÿ”ต UnderstandExplain the difference between program and process, and describe how fork() creates a child process with a copy of the parent's address space
๐ŸŸข ApplyWrite C programs using fork(), exec(), wait(), and exit() system calls and predict their output, including PID/PPID values
๐ŸŸข AnalyzeDifferentiate between zombie and orphan processes, analyse context switching overhead, and compare co-operating vs independent processes
๐ŸŸ  EvaluateEvaluate the process management failures in CoWIN/IRCTC crashes and propose solutions using process pooling and rate limiting
๐ŸŸ  CreateDesign a process monitoring tool and construct process family trees showing parent-child relationships across multiple fork() calls
Section C

Concept Explanation โ€” Process Management from Scratch

1. Process Concept โ€” Program vs Process

Plain English: A program is like a recipe written in a cookbook sitting on a shelf. It does nothing by itself. A process is you actually cooking that recipe โ€” you've gathered ingredients (memory), you're following steps (program counter), you're using the stove (CPU), and the dish is in progress. The same recipe (program) can be cooked by multiple people (processes) simultaneously.

๐Ÿ“‹ Program vs Process โ€” The Key Differences

AspectProgramProcess
NaturePassive entity (static)Active entity (dynamic)
ExistenceStored on disk (file)Exists in memory (RAM)
LifecycleNo lifecycle โ€” just existsCreated โ†’ Runs โ†’ Terminates
ResourcesNone consumedUses CPU, memory, I/O, files
MultiplicityOne program file on diskMultiple processes from same program
Indian AnalogyA recipe book on the shelfActually cooking the dish in the kitchen
Think of IRCTC's booking application. The booking.exe file sitting on the server is a program. When 50 lakh users click "Book Ticket" simultaneously, 50 lakh processes are spawned from that same program. Each process has its own passenger details, selected train, and payment status โ€” even though they all originated from the same program code.

A process in memory consists of 4 segments:

SegmentWhat It StoresAnalogy
Text (Code)The compiled program instructionsRecipe steps printed on paper
DataGlobal and static variablesPre-measured ingredients kept ready
HeapDynamically allocated memory (malloc)Extra ingredients fetched as needed during cooking
StackFunction calls, local variables, return addressesYour mental checklist โ€” "first chop onions, then fry, then add spices"
Students lose marks by writing "Process = Program in execution" without elaboration. Examiners want you to mention: (1) a process has its own memory space (text, data, heap, stack), (2) it has a PCB, (3) multiple processes can be created from the same program, and (4) process is dynamic while program is static. Write all four points for full marks.

2. Process Control Block (PCB) โ€” The Aadhaar Card of a Process

Every Indian citizen has an Aadhaar card โ€” a unique ID with your name, photo, address, and biometrics. Similarly, every process has a Process Control Block (PCB) โ€” a data structure maintained by the OS that stores everything about that process. When the OS needs to manage a process (pause it, resume it, kill it), it looks at the PCB.

๐Ÿ—‚๏ธ PCB Fields โ€” Every Field Explained

PCB FieldWhat It StoresAadhaar Analogy
Process ID (PID)Unique integer identifying the processYour 12-digit Aadhaar number
Process StateCurrent state: New, Ready, Running, Waiting, TerminatedYour current status โ€” employed, student, retired
Program Counter (PC)Address of the next instruction to executeWhich page of the recipe book you're on
CPU RegistersValues in accumulator, stack pointer, general-purpose registersWhat ingredients you're currently holding in your hands
Memory LimitsBase/limit registers, page table infoYour registered address โ€” where you live
Open Files ListFile descriptors for all open filesDocuments you're currently working with
Scheduling InfoPriority, scheduling queue pointers, CPU time usedYour place in the queue at a government office
I/O StatusList of I/O devices allocated, pending I/O requestsWhich counter/window is serving you
Accounting InfoCPU time consumed, time limits, job/process numbersYour bank passbook โ€” how much "CPU currency" you've spent
Parent PID (PPID)PID of the process that created this processYour father's Aadhaar number on your birth certificate
For GATE and university exams, memorise all PCB fields. A classic 5-mark question is: "Draw the structure of a PCB and explain each field." The fields most students forget are: I/O status, accounting info, and scheduling info. Include all 10 fields for full marks.
C Struct
// Simplified PCB structure (conceptual, not actual Linux kernel code)
struct PCB {
    int     pid;              // Process ID (unique)
    int     ppid;             // Parent Process ID
    enum    state;            // NEW, READY, RUNNING, WAITING, TERMINATED
    int     program_counter;  // Address of next instruction
    int     registers[16];   // CPU register snapshot
    int     priority;         // Scheduling priority
    void*   memory_base;      // Start of memory allocation
    int     memory_limit;     // Memory boundary
    int     open_files[256]; // File descriptor table
    long    cpu_time_used;    // Total CPU time consumed
};

3. Process States & State Transition Diagram

A process goes through 5 states during its lifetime โ€” just like a passenger on an Indian Railway journey:

StateMeaningRailway Analogy
NewProcess is being createdYou've just booked a ticket โ€” you're in the system but haven't reached the station yet
ReadyProcess is loaded in RAM, waiting for CPUYou're at the platform, bag packed, waiting for the train to arrive
RunningProcess is currently executing on CPUYou're on the train โ€” it's moving, you're traveling!
Waiting (Blocked)Process is waiting for I/O or an eventTrain stopped at a signal โ€” waiting for the track to clear
TerminatedProcess has finished executionYou've reached your destination and exited the station

State Transition Diagram (ASCII Art)

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ PROCESS STATE DIAGRAM โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ Admitted Scheduler Exit โ”Œโ”€โ”€โ”€โ”€โ”€โ” โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” Dispatch โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”€โ”€โ”€โ”€โ”€โ”€โ–บ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ NEW โ”‚ โ”‚ READY โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ โ”‚ RUNNING โ”‚ โ”‚ TERMINATED โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ–ฒ โ”‚ โ”‚ โ”‚ Interrupt / โ”‚ โ”‚ โ”‚ Time Quantum โ”‚ โ”‚ โ”‚ Expired โ”‚ โ”‚ โ”‚โ—„โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ โ”‚ โ”‚ I/O or Event โ”‚ โ”‚ Completed โ”‚ I/O or Event Wait โ”‚ โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ” โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”‚ WAITING โ”‚ โ”‚(BLOCKED) โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Every Transition Explained

TransitionWhen It HappensIndian Example
New โ†’ ReadyOS admits the process, loads it into memoryIRCTC accepts your booking request, puts you in the queue
Ready โ†’ RunningCPU scheduler picks this process (dispatch)Your token number is called at the bank counter
Running โ†’ ReadyTimer interrupt / time quantum expires (preemption)Bank clerk says "next please" โ€” you go back to waiting with your half-done form
Running โ†’ WaitingProcess needs I/O (disk read, network, user input)Clerk says "bring your PAN card photocopy from the Xerox shop" โ€” you leave the counter
Waiting โ†’ ReadyI/O operation completesYou return with the photocopy and rejoin the queue
Running โ†’ TerminatedProcess calls exit() or finishes executionYour work at the bank is done, you leave
There is NO direct transition from Waiting โ†’ Running! A process must go from Waiting โ†’ Ready โ†’ Running. After I/O completes, the process goes to the Ready queue and waits for the scheduler. Many students draw a direct arrow from Waiting to Running โ€” that's wrong and costs 1-2 marks in exams.
Can a process go from Ready โ†’ Terminated? In standard theory diagrams โ€” No. But in practice, a parent process can kill a child that's in the Ready state. Examiners usually expect the standard 5 transitions. If they ask for 6, add New โ†’ Terminated (process aborted during creation).

4. Operations on Processes โ€” fork(), exec(), wait(), exit()

4.1 fork() โ€” Creating a Child Process

fork() creates a new child process that is an almost exact copy of the parent. It's like a cell dividing โ€” one becomes two. Both parent and child continue executing from the line after fork().

๐Ÿ”€ How fork() Works โ€” Step by Step

  1. Parent process calls fork()
  2. OS creates a new PCB for the child process
  3. Child gets a copy of parent's text, data, heap, and stack segments
  4. Child gets a new unique PID, but its PPID = parent's PID
  5. fork() returns twice:
    • Returns child's PID (a positive number) to the parent
    • Returns 0 to the child
    • Returns -1 if fork fails (e.g., memory full)
  6. Both parent and child continue executing the next line after fork()
C
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main() {
    pid_t pid;

    printf("Before fork: I am process %d\n", getpid());

    pid = fork();  // This is where the magic happens!

    if (pid < 0) {
        fprintf(stderr, "Fork failed!\n");
        return 1;
    }
    else if (pid == 0) {
        // CHILD process โ€” fork() returned 0
        printf("CHILD:  My PID = %d, My Parent's PID = %d\n",
               getpid(), getppid());
    }
    else {
        // PARENT process โ€” fork() returned child's PID
        printf("PARENT: My PID = %d, Child's PID = %d\n",
               getpid(), pid);
    }

    printf("This line executes in BOTH parent and child! (PID: %d)\n",
           getpid());
    return 0;
}
Before fork: I am process 1234 PARENT: My PID = 1234, Child's PID = 1235 This line executes in BOTH parent and child! (PID: 1234) CHILD: My PID = 1235, My Parent's PID = 1234 This line executes in BOTH parent and child! (PID: 1235)
fork() is like a joint family dividing into nuclear families. When a son (child process) starts his own household, he takes a copy of the family assets (data), gets his own Aadhaar number (PID), but remembers his father's Aadhaar (PPID). Both families continue living independently โ€” but they started from the same origin.
Tricky fork() output question: If there are N fork() calls in sequence (no if-else), total processes created = 2^N. Two fork() calls = 4 processes. Three = 8. Students who forget that fork() duplicates the entire remaining code get this wrong.

4.2 exec() Family โ€” Replacing the Process Image

exec() replaces the current process's code with a completely different program. The PID remains the same, but the process is now running different code. It's like a person changing their career โ€” same person (PID), new job (program).

C
#include <stdio.h>
#include <unistd.h>

int main() {
    printf("Before exec: PID = %d\n", getpid());

    // Replace this process with the "ls -l" command
    execlp("ls", "ls", "-l", NULL);

    // This line NEVER executes if exec succeeds!
    printf("This won't print โ€” exec replaced us!\n");

    return 0;
}
The exec() family has 6 variants: execl, execlp, execle, execv, execvp, execve. The naming pattern: l = list of args, v = vector (array) of args, p = search PATH, e = pass environment. For exams, knowing execlp and execvp is enough.

4.3 wait() โ€” Parent Waits for Child

wait() makes the parent process pause and wait until one of its child processes terminates. This prevents zombie processes and allows the parent to collect the child's exit status.

C
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
    pid_t pid = fork();

    if (pid == 0) {
        // Child
        printf("Child (PID %d): Doing some work...\n", getpid());
        sleep(3);  // Simulate 3 seconds of work
        printf("Child: Done! Exiting.\n");
        return 42;  // Exit with status 42
    }
    else {
        // Parent
        int status;
        printf("Parent (PID %d): Waiting for child...\n", getpid());
        wait(&status);  // Block until child finishes
        printf("Parent: Child exited with status %d\n",
               WEXITSTATUS(status));
    }
    return 0;
}
Parent (PID 1234): Waiting for child... Child (PID 1235): Doing some work... Child: Done! Exiting. Parent: Child exited with status 42

4.4 exit() โ€” Terminating a Process

exit(status) terminates the calling process. The integer status is passed to the parent via wait(). Convention: exit(0) = success, non-zero = error.

Students confuse return from main() with exit(). In main(), return 0; and exit(0); are functionally the same. But inside any other function, return only exits that function, while exit() terminates the entire process immediately.

5. Zombie & Orphan Processes

5.1 Zombie Process โ€” "Dead But Not Buried"

A zombie process is a child that has terminated (called exit()), but its parent hasn't called wait() to collect its exit status. The child's PCB still exists in the process table โ€” taking up space but doing nothing. It's like a person who has died but whose death certificate hasn't been collected โ€” they're still in government records.

C โ€” Creating a Zombie
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main() {
    pid_t pid = fork();

    if (pid == 0) {
        // Child: exit immediately
        printf("Child (PID %d): I'm done. Becoming zombie...\n", getpid());
        exit(0);
    }
    else {
        // Parent: sleep without calling wait() โ€” child becomes zombie!
        printf("Parent (PID %d): Sleeping 30s. NOT calling wait().\n", getpid());
        printf("Run 'ps aux | grep Z' in another terminal to see the zombie!\n");
        sleep(30);  // During this 30s, child is a zombie
    }
    return 0;
}
$ ps aux | grep Z user 1235 0.0 0.0 0 0 pts/0 Z+ 14:30 0:00 [zombie_demo] <defunct>
Zombies are like unclaimed packages at a post office. The package (child) has arrived and is "done," but nobody (parent) came to collect it. It sits in the system, consuming space in the process table. Too many zombies? The process table gets full, and the OS can't create new processes โ€” similar to how an overloaded post office can't accept new parcels.

5.2 Orphan Process โ€” "Parent Left Without Me"

An orphan process is a child whose parent has terminated before the child. In Linux, orphans are "adopted" by the init process (PID 1) or systemd, which becomes their new parent and will call wait() for them.

C โ€” Creating an Orphan
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main() {
    pid_t pid = fork();

    if (pid == 0) {
        // Child: keep running after parent exits
        sleep(5);
        printf("Child (PID %d): My parent left! New parent PID = %d\n",
               getpid(), getppid());
        // getppid() will now return 1 (init) or systemd's PID
    }
    else {
        // Parent: exit immediately, abandoning the child
        printf("Parent (PID %d): I'm leaving! Child PID = %d\n",
               getpid(), pid);
        exit(0);
    }
    return 0;
}
Parent (PID 1234): I'm leaving! Child PID = 1235 $ Child (PID 1235): My parent left! New parent PID = 1 โ† Adopted by init!
PropertyZombie ProcessOrphan Process
WhatChild exited, parent didn't call wait()Parent exited before child
StateTerminated (Z state)Still running (adopted by init)
Dangerous?Yes โ€” fills up process tableNo โ€” init handles cleanup properly
FixParent must call wait() or use signal handlersNo fix needed โ€” OS handles it
AnalogyUnclaimed package at post officeChild at orphanage โ€” adopted by the state
GATE frequently asks: "Which is more dangerous โ€” zombie or orphan?" Answer: Zombie. Orphans are safely adopted by init. But zombies consume process table entries. If thousands accumulate, no new processes can be created (fork() returns -1). This is called a zombie leak.

6. Co-operating vs Independent Processes

PropertyIndependent ProcessCo-operating Process
Data SharingCannot affect or be affected by other processesShares data with other processes
ExecutionDeterministic โ€” same input โ†’ same output every timeNon-deterministic โ€” output depends on execution order
SynchronisationNot neededRequired (semaphores, mutexes, etc.)
ExampleTwo students taking different exams in different roomsTwo chefs cooking the same dish โ€” one chops, other fries
Indian Railways is a perfect example of co-operating processes. The reservation system, the PNR status checker, the coach allocation system, and the dynamic pricing engine are all separate processes that share data (the central seat database). If the reservation process adds a passenger without telling the allocation system, chaos follows. They must synchronise โ€” that's why you see "Confirming your booking..." delays on IRCTC.

Why do we need co-operating processes?

  1. Information Sharing: Multiple users accessing a shared database (like IRCTC seat availability)
  2. Computation Speedup: Break a large task into subtasks running in parallel (like MapReduce)
  3. Modularity: Build systems from separate interacting modules (microservices at Flipkart)
  4. Convenience: A user can edit a document, print, and compile code simultaneously

7. Context Switching โ€” The Hidden Cost of Multitasking

Plain English: Imagine you're studying Maths. Your phone rings โ€” it's your friend. You bookmark your Maths page, put the book down, talk for 5 minutes, then pick up Maths again from the bookmarked page. That entire process of saving your Maths state โ†’ switching to phone โ†’ restoring Maths state is a context switch. The 5 minutes on the phone was productive, but the 30 seconds of bookmarking + finding your page again was overhead โ€” wasted time.

๐Ÿ”„ Context Switch โ€” Step by Step

When the OS switches from Process A to Process B:

  1. Save state of Process A: Copy all CPU register values, program counter, and stack pointer into A's PCB
  2. Update A's PCB: Change A's state from Running to Ready (or Waiting)
  3. Move A's PCB: Place A's PCB into the appropriate queue (ready queue or wait queue)
  4. Select Process B: The scheduler picks B from the ready queue
  5. Load state of Process B: Copy B's saved register values, PC, and SP from B's PCB into the CPU
  6. Update B's PCB: Change B's state from Ready to Running
  7. Resume B: CPU starts executing B from where it last left off
CONTEXT SWITCH: Process Pโ‚€ โ†’ Process Pโ‚ Process Pโ‚€ Operating System Process Pโ‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚ RUNNING โ”‚ โ”‚ READY โ”‚ โ”‚ โ”‚ โ”€โ”€โ”€โ”€ interrupt/syscall โ”€โ”€โ”€โ”€โ–บ โ”‚ โ”‚ โ”‚ โ”‚ Save state to PCBโ‚€ โ”‚ โ”‚ โ”‚ READY โ”‚ Load state from PCBโ‚ โ”‚ โ”‚ โ”‚ โ”‚ โ—„โ”€โ”€โ”€โ”€ resume execution โ”€โ”€โ”€โ”€ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ RUNNING โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ—„โ”€โ”€โ”€ interrupt/syscall โ”€โ”€โ”€โ”€โ”€ โ”‚ โ”‚ โ”‚ โ”‚ Save state to PCBโ‚ โ”‚ READY โ”‚ โ”‚ RUNNING โ”‚ Load state from PCBโ‚€ โ”‚ โ”‚ โ”‚ โ”‚ โ”€โ”€โ”€โ”€ resume execution โ”€โ”€โ”€โ”€โ”€โ–บ โ”‚ โ”‚ โ–ผ โ–ผ โ–ผ โ–ผ

Context Switching Overhead Analysis

FactorImpactTypical Time
Register save/restoreMust save/load all CPU registers~1-2 microseconds
Memory mappingTLB flush, page table switch~5-10 microseconds
Cache invalidationCPU cache becomes useless for new process (cold cache)Indirect โ€” causes cache misses for ~100ฮผs
Pipeline flushCPU instruction pipeline must be flushed~10-20 cycles
Total overheadPer context switch~5-20 microseconds on modern hardware
Context switch time depends on hardware. Modern CPUs (Intel i7/AMD Ryzen) have hardware support for fast context switching. ARM processors in phones have slightly higher overhead. This is why phones with 8 cores still feel slower than a 4-core desktop โ€” context switch overhead on mobile CPUs is higher.
CoWIN's crash was a context switching disaster. With 20 million requests, the server was running thousands of processes simultaneously. If context switch overhead is ~10ฮผs and the CPU switches 100,000 times per second, that's 1 full second per second spent just on switching โ€” leaving zero time for actual work. This is called thrashing โ€” the system is so busy managing processes that it can't execute any of them.
Calculate: If a system has 500 active processes and each context switch takes 15 microseconds, and the scheduler switches every 10 milliseconds (time quantum), what percentage of CPU time is spent on context switching alone? (Answer: 500 ร— 15ฮผs = 7.5ms per full round. In a 10ms window, 75% is wasted on switching!)
Section D

Learn by Doing โ€” 3-Tier Lab Structure

๐ŸŸข Tier 1 โ€” GUIDED TASK: fork() Family Tree in C

โฑ๏ธ 45โ€“60 minutesBeginnerWSL / Linux / Mac required

Objective:

Write a C program where a parent creates 2 children. Each child prints its PID and PPID, forming a family tree.

Step 1: Create the Source File

Open terminal (WSL on Windows, or native Linux/Mac terminal). Create a file:

Bash
nano family_tree.c

Step 2: Write the Code

C
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
    pid_t pid1, pid2;

    printf("========================================\n");
    printf("  PROCESS FAMILY TREE DEMO\n");
    printf("========================================\n");
    printf("PARENT: PID = %d\n\n", getpid());

    // Create first child
    pid1 = fork();

    if (pid1 == 0) {
        // First child
        printf("  CHILD 1: PID = %d, Parent PID = %d\n",
               getpid(), getppid());
        printf("  CHILD 1: I am the elder sibling!\n\n");
        sleep(2);
        return 0;  // IMPORTANT: Child must exit here!
    }

    // Create second child (only parent reaches here)
    pid2 = fork();

    if (pid2 == 0) {
        // Second child
        printf("  CHILD 2: PID = %d, Parent PID = %d\n",
               getpid(), getppid());
        printf("  CHILD 2: I am the younger sibling!\n\n");
        sleep(2);
        return 0;  // IMPORTANT: Child must exit here!
    }

    // Only parent reaches here
    int status;
    waitpid(pid1, &status, 0);
    printf("PARENT: Child 1 (PID %d) exited.\n", pid1);

    waitpid(pid2, &status, 0);
    printf("PARENT: Child 2 (PID %d) exited.\n", pid2);

    printf("\n========================================\n");
    printf("  FAMILY TREE:\n");
    printf("      Parent (PID %d)\n", getpid());
    printf("       /          \\\n");
    printf("  Child1 (%d)   Child2 (%d)\n", pid1, pid2);
    printf("========================================\n");

    return 0;
}

Step 3: Compile

Bash
gcc -o family_tree family_tree.c

Step 4: Run

Bash
./family_tree

Expected Output:

======================================== PROCESS FAMILY TREE DEMO ======================================== PARENT: PID = 5001 CHILD 1: PID = 5002, Parent PID = 5001 CHILD 1: I am the elder sibling! CHILD 2: PID = 5003, Parent PID = 5001 CHILD 2: I am the younger sibling! PARENT: Child 1 (PID 5002) exited. PARENT: Child 2 (PID 5003) exited. ======================================== FAMILY TREE: Parent (PID 5001) / \ Child1 (5002) Child2 (5003) ========================================
Forgetting return 0; in child blocks is the #1 bug. Without it, both children will continue executing the parent's code and create their own children โ€” resulting in 4 processes instead of 3. Always terminate child blocks explicitly.

Step 5: Verify with System Tools

While the program runs (increase sleep to 30 seconds), open another terminal:

Bash
# See the process tree
pstree -p | grep family_tree

# Alternative: ps command
ps -ef | grep family_tree

๐ŸŽ‰ Congratulations! You've created your first process family tree. Take a screenshot โ€” this is your portfolio piece!

๐ŸŸก Tier 2 โ€” SEMI-GUIDED TASK: Zombie & Orphan Process Demos

โฑ๏ธ 60โ€“90 minutesIntermediateHints provided, you fill the gaps

Task A: Create a Zombie Process

Write a C program that creates a zombie. Verify it using ps.

Hints:

  1. Fork a child process
  2. Make the child call exit(0) immediately
  3. Make the parent NOT call wait() โ€” instead, sleep(30)
  4. In another terminal, run: ps aux | grep Z โ€” you should see the zombie with state "Z+"
  5. After parent's sleep ends, the zombie disappears (parent exits, init cleans up)

Task B: Create an Orphan Process

Write a C program where the parent exits first, leaving the child orphaned.

Hints:

  1. Fork a child process
  2. Make the parent call exit(0) immediately
  3. Make the child sleep(10), then print its new PPID
  4. The child's new PPID should be 1 (init) or the PID of systemd
  5. Key observation: the child continues running even after the parent dies
Stretch Goal: Write a single program that creates both a zombie AND an orphan (using two fork() calls). Add comments explaining the lifecycle of each.

๐Ÿ”ด Tier 3 โ€” OPEN CHALLENGE: Real-Time Process Monitor

โฑ๏ธ 2โ€“3 hoursAdvancedNo instructions โ€” build from scratch

The Brief:

Build a real-time process monitor in Python or Bash that tracks process creation and termination on your system.

Requirements:

  1. List all running processes with PID, PPID, state, CPU%, and memory%
  2. Detect new processes โ€” poll every 2 seconds and show newly created processes
  3. Detect terminated processes โ€” show processes that disappeared since last check
  4. Filter zombies โ€” highlight any zombie processes in red (use ANSI colour codes)
  5. Show process tree โ€” display parent-child relationships for a given PID

Tools You Might Use:

  • Python: psutil library, os module, subprocess
  • Bash: ps, pstree, top, watch, diff
A polished version of this script is a real freelance deliverable. System administrators pay โ‚น3,000โ€“โ‚น10,000 for custom monitoring scripts. Add email alerts for zombie detection and you have a production-ready tool. Put it on GitHub with a good README.
Section E

Industry Spotlight โ€” A Day in the Life

๐Ÿ‘จโ€๐Ÿ’ป Vikram Iyer, 27 โ€” Systems Engineer at Amazon India, Hyderabad

Background: B.Tech (CSE) from NIT Warangal. Fascinated by how Linux manages millions of processes on Amazon's servers. Got placed through campus recruitment after excelling in OS and Computer Networks.

A Typical Day:

9:00 AM โ€” Morning standup with the EC2 infrastructure team. Review overnight alerts โ€” any processes that crashed or leaked memory on production servers.

10:00 AM โ€” Use strace to trace system calls on a misbehaving process. Found that a process was doing 10,000 unnecessary fork() calls per minute โ€” causing context switching overhead on the host machine.

11:30 AM โ€” Use gdb (GNU Debugger) to attach to a running process and inspect its state. Found a race condition between two co-operating processes sharing a database connection.

1:00 PM โ€” Lunch at Amazon's cafeteria. Discuss kernel tuning parameters with a senior engineer โ€” they're adjusting the scheduler's time quantum for better process throughput.

2:00 PM โ€” Write a systemd service file for a new microservice. Configure process restart policies, resource limits (max memory, max CPU), and logging.

4:00 PM โ€” Use perf to profile context switching overhead on a busy server. Found that reducing the number of worker processes from 500 to 50 (using process pooling) cut overhead by 80%.

5:30 PM โ€” Learning session: studying Linux kernel source code for process scheduling (CFS โ€” Completely Fair Scheduler).

DetailInfo
Tools Used DailyLinux CLI, strace, gdb, perf, systemd, htop, ps, /proc filesystem, Python scripts
Entry Salary (2024)โ‚น5โ€“8 LPA + benefits
Mid-Level (3โ€“5 yrs)โ‚น12โ€“22 LPA
Senior (7+ yrs)โ‚น25โ€“50 LPA
Companies HiringAmazon, Google, Microsoft, Flipkart, Oracle, Red Hat, VMware, Samsung R&D, Qualcomm, TCS, Infosys (ISU), HCLTech
Section F

Earn With It โ€” Freelance & Income Roadmap

๐Ÿ’ฐ Your Earning Path After This Chapter

Portfolio Piece: "Linux Process Monitor Script" โ€” a Python/Bash tool that monitors processes, detects zombies, and shows process trees. Put it on GitHub with a professional README.

Beginner Gig Ideas:

โ€ข Process monitoring scripts for small servers โ€” โ‚น3,000โ€“โ‚น10,000

โ€ข systemd service file creation for startups โ€” โ‚น2,000โ€“โ‚น5,000

โ€ข Linux server health-check automation scripts โ€” โ‚น5,000โ€“โ‚น15,000

โ€ข DevOps interview prep tutoring (process management concepts) โ€” โ‚น500โ€“โ‚น1,000/hour

PlatformBest ForTypical Rate
InternshalaLinux admin internshipsโ‚น10,000โ€“โ‚น25,000/month
FiverrShell script gigs, server monitoring$15โ€“$80/gig (โ‚น1,200โ€“โ‚น6,500)
UpworkDevOps / Linux sysadmin projects$20โ€“$50/hour
LinkedInFreelance DevOps consultingโ‚น5,000โ€“โ‚น15,000/project
ToptalSenior DevOps roles (after experience)$50โ€“$100/hour

โฑ๏ธ Time to First Earning: 3โ€“4 weeks (complete Tier 1 & 2 labs, build GitHub portfolio, apply on Internshala for Linux/DevOps internships)

The #1 skill companies test in Linux interviews: process management. "What happens when you type ls in the terminal?" Answer: The shell calls fork() to create a child process, then the child calls exec("ls") to replace itself with the ls program, parent calls wait() to wait for ls to finish. Knowing this wins you the job.
Section G

MCQ Assessment Bank โ€” 30 Questions (Bloom's Mapped)

Remember / Identify (Q1โ€“Q5)

Q1

A process is different from a program because:

  1. A process is stored on disk
  2. A process is an active entity in memory with its own PCB, while a program is a passive file on disk
  3. A program can use CPU directly
  4. There is no difference
Remember
โœ… Answer: (B) โ€” A program is a static file (executable on disk). A process is the running instance with allocated memory, a PCB, and CPU time. Multiple processes can be created from the same program.
Q2

Which of the following is NOT a field in the Process Control Block (PCB)?

  1. Process ID (PID)
  2. Program Counter
  3. Hard Disk RPM
  4. CPU Register values
Remember
โœ… Answer: (C) โ€” Hard Disk RPM is a hardware specification, not a process attribute. PCB stores PID, PC, registers, state, memory limits, open files, scheduling info, and I/O status.
Q3

The correct sequence of process states is:

  1. New โ†’ Running โ†’ Ready โ†’ Terminated
  2. New โ†’ Ready โ†’ Running โ†’ Waiting/Terminated
  3. Ready โ†’ New โ†’ Running โ†’ Waiting
  4. Running โ†’ New โ†’ Ready โ†’ Terminated
Remember
โœ… Answer: (B) โ€” A process starts as New, moves to Ready (loaded in memory), then Running (CPU assigned). From Running, it can go to Waiting (I/O) or Terminated (done).
Q4

The fork() system call returns:

  1. Always returns 0
  2. Returns child's PID to parent and 0 to child
  3. Returns parent's PID to both
  4. Returns nothing
Remember
โœ… Answer: (B) โ€” fork() returns twice: the child's PID (positive integer) to the parent, and 0 to the child. Returns -1 on failure.
Q5

A zombie process is created when:

  1. A process uses too much memory
  2. A child process terminates but the parent hasn't called wait()
  3. The CPU overheats
  4. Two processes deadlock
Remember
โœ… Answer: (B) โ€” A zombie is a terminated child whose exit status hasn't been collected by the parent via wait(). Its PCB remains in the process table, consuming an entry.

Understand / Explain (Q6โ€“Q10)

Q6

Why is there no direct transition from Waiting state to Running state?

  1. Because the CPU is always free
  2. Because after I/O completes, the process must re-enter the Ready queue and wait for the scheduler to assign CPU
  3. Because waiting processes are always terminated
  4. Because the OS doesn't track waiting processes
Understand
โœ… Answer: (B) โ€” The scheduler follows a queue-based approach. After I/O completion, the process moves to the Ready queue and competes for CPU like everyone else. Direct Waitingโ†’Running would bypass the scheduler's fairness policy.
Q7

Explain what happens to the address space when fork() is called:

  1. The child shares the same memory as the parent
  2. The child gets a copy of the parent's text, data, heap, and stack segments in its own memory space
  3. The parent's memory is deleted
  4. No memory is allocated to the child
Understand
โœ… Answer: (B) โ€” fork() creates a copy of the parent's entire address space for the child (modern systems use copy-on-write for efficiency). Both operate independently after fork().
Q8

How does exec() differ from fork()?

  1. exec() creates a new process; fork() replaces the image
  2. fork() creates a new child process; exec() replaces the current process's code with a new program without creating a new process
  3. Both do the same thing
  4. exec() only works on Windows
Understand
โœ… Answer: (B) โ€” fork() creates a new process (new PID). exec() replaces the current process's program image (same PID, different code). They're often used together: fork() then exec() in the child.
Q9

Why does the OS need to save CPU register values during a context switch?

  1. To increase CPU speed
  2. So that when the process resumes later, it can continue exactly from where it stopped โ€” registers hold the process's computation state
  3. To delete the process
  4. Registers are never saved
Understand
โœ… Answer: (B) โ€” CPU registers hold intermediate computation values (partial calculations, loop counters, memory addresses). Without saving them, the process would lose its work and have to start over.
Q10

What happens to an orphan process in Linux?

  1. It is immediately killed
  2. It becomes a zombie
  3. It is adopted by the init process (PID 1), which becomes its new parent
  4. It continues with no parent forever
Understand
โœ… Answer: (C) โ€” Linux's init (or systemd) process adopts all orphans. This ensures every process has a parent that will eventually call wait() to clean up. Orphans are safe; zombies are the real problem.

Apply / Demonstrate (Q11โ€“Q15)

Q11

What is the total number of processes created by the following code? fork(); fork(); fork();

  1. 3
  2. 6
  3. 7
  4. 8
Apply
โœ… Answer: (D) 8 โ€” Each fork() doubles the number of processes. After 3 fork() calls: 2ยณ = 8 total processes (including the original). New processes created = 7.
Q12

In the following code, how many times is "Hello" printed?
fork(); printf("Hello\n"); fork(); printf("Hello\n");

  1. 2
  2. 4
  3. 6
  4. 8
Apply
โœ… Answer: (C) 6 โ€” After first fork(): 2 processes each print "Hello" (2 prints). Then each forks again: 4 processes each print "Hello" (4 prints). Total = 2 + 4 = 6.
Q13

To run the ls -la command from within a C program using exec, the correct call is:

  1. execlp("ls", "ls", "-la", NULL);
  2. exec("ls -la");
  3. fork("ls -la");
  4. run("ls", "-la");
Apply
โœ… Answer: (A) โ€” execlp searches PATH for "ls", passes arguments as a list (l), and requires NULL termination. The first "ls" is the path, the second "ls" is argv[0] by convention.
Q14

A parent creates a child using fork(). The parent then calls wait(&status). If the child exits with exit(5), what value does WEXITSTATUS(status) return?

  1. 0
  2. 5
  3. -1
  4. Undefined
Apply
โœ… Answer: (B) 5 โ€” WEXITSTATUS(status) extracts the exit code passed to exit() by the child. The child called exit(5), so the macro returns 5.
Q15

You need to write a shell that executes user commands. The correct approach using system calls is:

  1. Directly call exec() in the shell's main process
  2. fork() a child, call exec() in the child to run the command, parent calls wait() for the child to finish
  3. Use only wait() without fork()
  4. Call exit() after every command
Apply
โœ… Answer: (B) โ€” This is exactly how bash/zsh work! The shell fork()s a child, the child exec()s the command (replacing itself), and the shell parent wait()s for completion before showing the next prompt.

Analyze / Compare (Q16โ€“Q20)

Q16

Compare zombie and orphan processes. Which is more harmful to system stability?

  1. Orphan โ€” because it runs without a parent
  2. Zombie โ€” because it occupies process table entries without releasing them, potentially filling the process table
  3. Both are equally harmful
  4. Neither is harmful
Analyze
โœ… Answer: (B) โ€” Zombies fill the process table. When the table is full, no new processes can be created (fork fails). Orphans are safely adopted by init and cleaned up properly.
Q17

Analyse why context switching overhead increases when the number of processes increases significantly:

  1. Because each process needs more RAM
  2. Because the CPU spends more time saving/restoring process states and less time doing actual work, and cache/TLB misses increase
  3. Because the disk becomes full
  4. Because context switching doesn't cause overhead
Analyze
โœ… Answer: (B) โ€” More processes = more frequent context switches. Each switch flushes the TLB and CPU cache, causing cold-start delays. With thousands of processes, the system thrashes โ€” spending more time switching than computing.
Q18

Differentiate between the text segment and the stack segment of a process:

  1. Both store the same data
  2. Text stores executable code (read-only, shared); Stack stores function calls, local variables, and return addresses (read-write, per-process)
  3. Stack stores the program binary
  4. Text is on disk; Stack is on the network
Analyze
โœ… Answer: (B) โ€” Text segment is the compiled machine code (immutable). Stack is dynamic โ€” grows/shrinks with function calls, stores local variables, return addresses, and function parameters.
Q19

Analyse why fork() followed by exec() is used instead of a single "create process with new program" call:

  1. Because exec() is faster alone
  2. Separating creation (fork) from program loading (exec) gives flexibility โ€” the child can set up file descriptors, environment variables, and pipes between fork and exec
  3. There is no reason; it's just historical
  4. Because exec() creates a new process
Analyze
โœ… Answer: (B) โ€” Between fork() and exec(), the child can redirect stdin/stdout (for pipes), change directories, set up signal handlers, and close unnecessary file descriptors. This separation enables Unix pipes like ls | grep .c.
Q20

Compare independent and co-operating processes in the context of IRCTC's ticket booking system:

  1. All IRCTC processes are independent
  2. The booking process, payment gateway process, and seat allocation process are co-operating processes that share the seat database and must synchronise to prevent double-booking
  3. Co-operating processes don't need synchronisation
  4. IRCTC uses only one process
Analyze
โœ… Answer: (B) โ€” If the booking and allocation processes don't synchronise, two users could book the same seat simultaneously (race condition). This is why IRCTC shows "Processing..." โ€” synchronisation takes time.

Evaluate / Judge (Q21โ€“Q25)

Q21

CoWIN crashed when 2 crore users hit simultaneously. Evaluate which process management concept was the primary failure point:

  1. The programming language was wrong
  2. Excessive process creation without pooling caused context switching overhead to consume nearly all CPU time, leaving no capacity for actual request processing
  3. The servers had too much RAM
  4. The database was too fast
Evaluate
โœ… Answer: (B) โ€” Each user request spawned a new process. Without process pooling (reusing a fixed pool of worker processes), the OS was drowning in context switches. The fix was implementing process pools and queue-based request handling.
Q22

A developer's server has 10,000 zombie processes. They say "zombies use no CPU, so they're harmless." Evaluate this claim:

  1. Correct โ€” zombies are completely harmless
  2. Incorrect โ€” while zombies don't use CPU, they occupy entries in the process table (finite size). When the table fills up, no new processes can be created, causing fork() to fail for ALL programs
  3. Correct โ€” zombies are automatically cleaned
  4. Incorrect โ€” zombies use 100% CPU
Evaluate
โœ… Answer: (B) โ€” The developer is partially right (no CPU) but dangerously wrong about harm. The process table has a maximum size (typically 32,768 on Linux). 10,000 zombies waste ~30% of available process slots.
Q23

Evaluate: "Using exec() without fork() first is always a mistake." Is this true?

  1. True โ€” exec must always follow fork
  2. False โ€” exec() without fork() is valid when you intentionally want to replace the current process (e.g., a login shell calling exec to replace itself with the user's shell)
  3. False โ€” exec() can create new processes
  4. True โ€” exec() crashes without fork()
Evaluate
โœ… Answer: (B) โ€” exec() without fork() is used when you want the current process to become a different program entirely. The login process, for example, exec()s into bash after authentication โ€” it doesn't need to fork first.
Q24

IRCTC uses a single-process model for handling Tatkal bookings. Evaluate this design decision:

  1. Excellent โ€” one process is simplest
  2. Terrible โ€” a single process can only handle one booking at a time. With 25 million requests, the queue would be hours long. Multi-process or multi-threaded architecture is essential
  3. Good if the server is fast enough
  4. It doesn't matter how many processes are used
Evaluate
โœ… Answer: (B) โ€” Single-process means sequential processing. At 1 booking/100ms, 25 million bookings = 2.5 million seconds โ‰ˆ 29 days! Multi-process with pooling is mandatory for any high-traffic Indian platform.
Q25

A team argues: "We should increase the time quantum from 10ms to 1000ms to reduce context switching." Evaluate the trade-off:

  1. Great idea with no downsides
  2. Reduces context switching overhead but increases response time for interactive processes โ€” a 1s quantum means a user might wait up to 1s for their keypress to be processed, making the system feel unresponsive
  3. Terrible idea โ€” bigger quantum always causes crashes
  4. Time quantum has no effect on performance
Evaluate
โœ… Answer: (B) โ€” This is a classic trade-off: large quantum โ†’ less switching overhead but poor interactivity. Small quantum โ†’ fast response but high switching overhead. The optimal value depends on the system's workload (batch vs interactive).

Create / Design (Q26โ€“Q30)

Q26

Design a solution to prevent zombie processes in a long-running server application:

  1. Never use fork()
  2. Use signal(SIGCHLD, SIG_IGN) to automatically clean up child processes, or install a SIGCHLD handler that calls waitpid(-1, NULL, WNOHANG) in a loop
  3. Restart the server every hour
  4. Kill all child processes immediately after creation
Create
โœ… Answer: (B) โ€” Setting SIGCHLD to SIG_IGN tells the OS to auto-reap children. Alternatively, a signal handler with waitpid(-1, NULL, WNOHANG) collects all finished children without blocking. This is the industry-standard approach.
Q27

Design a process architecture for a CoWIN-like vaccination booking system that can handle 2 crore concurrent users without crashing:

  1. One process per user request
  2. Process pooling (pre-fork a fixed number of worker processes), queue-based request handling, load balancing across multiple servers, and rate limiting at the gateway
  3. Use a single thread for all users
  4. Turn off the server during peak hours
Create
โœ… Answer: (B) โ€” Process pooling (e.g., 200 workers) reuses processes instead of creating new ones. A request queue buffers overflow. Load balancers distribute across servers. Rate limiting prevents any single user from overwhelming the system.
Q28

Create a process family tree for the following code. How many leaf processes exist?

pid = fork();
if (pid == 0) {
    fork();
}
fork();
  1. 2 leaf processes
  2. 3 leaf processes
  3. 4 leaf processes
  4. 5 leaf processes
Create
โœ… Answer: (C) 4 leaf processes โ€” First fork creates P1 (parent) and P2 (child). P2 forks P3. Then all three (P1, P2, P3) execute the final fork, creating P4, P5, P6. But P1's child from the final fork is P4, P2's is P5, P3's is P6. Leaf processes (those with no children) = P4, P5, P6, and P3's last fork child = 4 leaves.
Q29

Design a shell command pipeline cat file.txt | grep "error" | wc -l using fork/exec/wait. How many processes are created?

  1. 1 process
  2. 3 child processes (one for cat, one for grep, one for wc), connected by 2 pipes
  3. 6 processes
  4. No processes are needed
Create
โœ… Answer: (B) โ€” The shell creates 3 child processes. Each child exec()s one command. Pipes connect stdout of cat โ†’ stdin of grep โ†’ stdin of wc. The shell (parent) waits for all three to finish.
Q30

Design a process monitoring alert system for Amazon's EC2 servers. Which metrics should trigger automatic alerts?

  1. Only CPU temperature
  2. Zombie process count > threshold, process table usage > 80%, context switch rate > 50,000/sec, any process consuming > 90% CPU for > 5 minutes, fork() failure rate increasing
  3. Number of keyboard presses
  4. Only RAM usage
Create
โœ… Answer: (B) โ€” A production monitoring system tracks: zombie count (leak detection), process table saturation (capacity), context switch rate (overhead), CPU hog processes (runaway code), and fork failures (resource exhaustion). This is what tools like Datadog and Prometheus monitor at Amazon.
Section H

Short Answer Questions (2โ€“3 marks each)

Question 1 (2 marks)

Differentiate between a program and a process. Give one real-world analogy.

Question 2 (3 marks)

Draw the process state transition diagram showing all 5 states and label each transition with the event that triggers it.

Question 3 (3 marks)

Explain what happens step-by-step when fork() is called. What values does it return to the parent and child? Write a 5-line C code snippet demonstrating fork() with PID printing.

Question 4 (2 marks)

Differentiate between zombie and orphan processes. Which one is more dangerous and why?

Question 5 (3 marks)

Explain context switching with a diagram. List 3 sources of overhead during a context switch and explain why context switching is called "pure overhead."

Section I

Long Answer & Case Studies (10 marks each)

๐Ÿ“‹ Case Study 1: CoWIN Vaccine Portal Crash โ€” A Process Management Post-Mortem (10 marks)

On June 21, 2021, India opened COVID-19 vaccination registration for all adults (18+). The CoWIN portal, managed by the National Informatics Centre (NIC), received approximately 2 crore (20 million) concurrent requests at 4:00 PM. The portal became completely unresponsive. Users saw blank pages, OTPs failed, and vaccination slots couldn't be booked for several hours.

Post-incident analysis revealed: the server's process table filled up within 30 seconds of launch. Each HTTP request created a new process. Context switching overhead consumed 92% of CPU time. The remaining 8% was insufficient to process even basic page loads.

Answer the following:

  1. (2 marks) Explain the role of the Process Control Block in this scenario. Why did the process table fill up? What happens when the process table is full?
  2. (3 marks) Calculate: If each process creation takes 0.5ms and context switch takes 15ฮผs, and the server had a 4-core CPU with a process table limit of 32,768 โ€” how quickly would the table fill? How many context switches per second would occur with 32,768 active processes?
  3. (2 marks) Propose a process pooling solution. How does pre-forking a fixed pool of worker processes prevent this crash?
  4. (3 marks) Design a complete architecture (with diagram) for a "crash-proof" CoWIN system using concepts from this chapter: process pooling, rate limiting, queue-based request handling, and graceful process termination.

๐Ÿ“‹ Case Study 2: Aadhaar Biometric Authentication โ€” Process Management at 100 Million Requests/Day (10 marks)

India's Aadhaar system, managed by UIDAI, processes over 100 million biometric authentication requests daily. When a citizen places their fingerprint on a scanner at a bank for eKYC, the system must: capture the biometric, create a process to handle the authentication request, match against 1.4 billion stored fingerprints, and return a yes/no result โ€” all within 200 milliseconds.

The system runs on distributed Linux servers. Each authentication spawns a child process that performs the biometric matching. The parent process manages the connection pool and request queue.

Answer the following:

  1. (2 marks) Identify which process operations (fork, exec, wait, exit) are used in the authentication flow. Draw the process lifecycle for a single authentication request.
  2. (3 marks) With 100 million requests/day, calculate the average requests per second. If each request process lives for 200ms, how many concurrent processes exist at any moment? What are the implications for the process table and context switching?
  3. (2 marks) Explain how zombie processes could accumulate in this system if the parent process has a bug in its wait() handling. What would be the consequences?
  4. (3 marks) Design a process management strategy for Aadhaar's authentication servers that minimises context switching, prevents zombie accumulation, and ensures 99.99% uptime. Include specific system calls and Linux commands you would use.
Section J

Chapter Summary โ€” Tweet-Sized Bullet Points

๐Ÿ“ Key Takeaways

  • ๐Ÿ“ฆ Program vs Process: Program = static file on disk (recipe). Process = active entity in memory with its own PCB, registers, and state (cooking the dish).
  • ๐Ÿ—‚๏ธ PCB = Aadhaar of a process: Contains PID, state, program counter, registers, memory limits, open files, scheduling info, accounting info.
  • ๐Ÿ”„ 5 process states: New โ†’ Ready โ†’ Running โ†’ Waiting โ†’ Terminated. No direct Waitingโ†’Running transition!
  • ๐Ÿด fork(): Creates child process (copy of parent). Returns child's PID to parent, 0 to child, -1 on failure.
  • ๐Ÿ”€ exec(): Replaces current process's code with a new program. Same PID, different code. Code after exec() never executes.
  • โณ wait(): Parent blocks until child terminates. Prevents zombies. Collects child's exit status.
  • ๐Ÿ’€ Zombie: Child exited, parent didn't wait(). Occupies process table entry. Dangerous in large numbers.
  • ๐Ÿ‘ถ Orphan: Parent exited before child. Safely adopted by init (PID 1). Not dangerous.
  • ๐Ÿค Co-operating processes share data and need synchronisation (like IRCTC's booking + allocation systems).
  • โšก Context switching saves/restores process state via PCB. ~5-20ฮผs overhead per switch. Too many processes โ†’ thrashing.
  • ๐Ÿ’ฅ CoWIN crashed because uncontrolled process creation โ†’ process table full โ†’ context switching overhead โ†’ CPU thrashing.
  • ๐Ÿ’ฐ Earn NOW: Linux process monitoring scripts on GitHub โ†’ freelance DevOps gigs โ‚น3Kโ€“โ‚น10K on Internshala/Fiverr.
Section K

My Earning Checkpoint โ€” Self-Assessment

Skill LearnedTool PractisedPortfolio Item AddedGig Ready?
Process Concept & PCBConceptual / DiagramsProcess state diagramโœ… Yes โ€” can explain in interviews
fork() / exec() / wait()GCC on Linux/WSLFamily Tree C programโœ… Yes โ€” core Linux interview skill
Zombie & Orphan ProcessesC + ps/pstree commandsZombie & Orphan demo programsโœ… Yes โ€” debugging skill for DevOps
Context SwitchingConceptual + CalculationOverhead analysis notesโœ… Yes โ€” system tuning knowledge
Process MonitoringPython / Bash scriptingLinux Process Monitor Scriptโœ… Yes โ€” โ‚น3Kโ€“โ‚น10K/project on Fiverr
System Design (CoWIN)Architecture diagramsCrash analysis case studyโœ… Yes โ€” shows system thinking in interviews
Minimum Viable Earning Setup after this chapter: A GitHub repo with process management C programs + a Python process monitor script + an Internshala/LinkedIn profile highlighting Linux & OS skills = you can land DevOps internships at โ‚น15Kโ€“โ‚น25K/month while still in college.

โœ… Unit 2 complete. MCQs: 30. Ready for Unit 3: CPU Scheduling!

[QR: Link to EduArtha video tutorial โ€” Process Management]