Operating Systems chapters (5)
  1. 01OS Structures & System Calls
  2. 02Process & Thread Management
  3. 03CPU Scheduling Algorithms
  4. 04Process Synchronization & Deadlocks
  5. 05Memory Management & Virtual Memory

Chapter 02 · OS

Process & Thread Management

6 topics · 2 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

A process is a program in execution with its own address space and a PCB; threads are lightweight units of execution inside a process.

This chapter covers process states and transitions, the PCB, fork/exec/wait, threads vs processes, user vs kernel threads and context switching cost.

fork-counting output questions and thread-model comparisons appear almost every year in GATE and university exams.

Web servers (process or thread per request), shell implementation, multi-threaded apps, and debugging zombie processes.

1

Process States & PCB

A process is a program in execution: code (text), data, heap, stack plus CPU context. The OS tracks each process in a Process Control Block (PCB). States: New, Ready, Running, Waiting (Blocked), Terminated.

In short: A program is a recipe on disk; a process is the cook actually cooking, with notes about progress kept in the PCB.

CPU runs processes in turns

Think about it

PCB lets the OS pause a process and resume it later exactly where it stopped.

Transitions

  • 1New→Ready (admitted)
  • 2Ready→Running (scheduler dispatch)
  • 3Running→Ready (preempted by timer/higher priority)
  • 4Running→Waiting (I/O or event wait)
  • 5Waiting→Ready (I/O completes)
  • 6Running→Terminated (exit)

Waiting→Running is NOT a valid direct transition: after the event the process must wait in the ready queue.

The PCB holds: process ID, state, program counter, CPU registers, scheduling info (priority, queue pointers), memory-management info (page table or base/limit), accounting info, open file and I/O status.

Queues: job queue, ready queue, device queues.

Schedulers: long-term (admits jobs, controls degree of multiprogramming), short-term (CPU scheduler, runs often), medium-term (swaps processes out and in).

Key points

  • PCB: Kernel data structure storing all information needed to manage a process.
  • Dispatcher: Module that gives the CPU to the process chosen by the short-term scheduler.
  • Degree of multiprogramming: Number of processes in memory.
  • Swapping: Moving a process between memory and disk (medium-term scheduling).
  • Valid: Ready→Running, Running→Ready, Running→Waiting, Waiting→Ready. Invalid: Waiting→Running, Ready→Waiting.
  • Dispatch latency = time dispatcher takes to stop one process and start another.
2

fork() and exec() Operations

fork() creates a child process that is a copy of the parent. It returns 0 in the child and the child PID in the parent (-1 on failure). exec() replaces the current process image with a new program. wait() makes the parent block until a child terminates and collects its status.

In short: fork clones the process; exec turns the clone into a different program; wait lets the parent pick up the result.

Think about it

This is the Unix model of process creation and the favourite source of output-prediction questions.

After fork both processes continue from the next statement with separate address spaces (copy-on-write makes this cheap).

A shell implements a command by fork then exec in the child and wait in the parent.

Zombie: a child that has terminated but whose exit status has not been read by wait, so its PCB entry remains.

Orphan: a child whose parent terminated first; it is adopted by init/systemd.

Counting rule

a program that executes n fork() calls unconditionally creates 2^n processes in total, i.

e.

2^n - 1 children.

If fork is inside an if on the return value, count branch by branch.

Key points

  • Copy-on-write: Parent and child share pages until one writes, then the page is copied.
  • Zombie: Terminated process whose status is not yet collected by its parent.
  • Orphan: Process whose parent has terminated first.
  • exec() does not create a process and does not return on success; PID stays the same, memory image is replaced, open file descriptors normally stay open.
  • fork() output tracing: for fork(); fork(); printf("X"); X is printed 4 times; for if(fork()==0){fork();} printf("X"); X is printed 3 times; for fork() && fork(): the second fork runs only in the parent of the first fork, giving 3 processes.
  • Process tree: with n unconditional forks the number of processes is 2^n; number of processes that return 0 from some fork (children) is 2^n − 1.

Example

Code
Shell-like fork + exec + wait:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void) {
    pid_t pid = fork();
    if (pid == 0) {
        execlp("ls", "ls", "-l", NULL);   // child becomes ls
    } else if (pid > 0) {
        wait(NULL);                        // parent waits
        printf("child done ");
    }
    return 0;
}
3

Zombie & Orphan Processes

A zombie (defunct) process has finished execution but still has an entry in the process table because its parent has not yet called wait() to read its exit status. An orphan process is a running process whose parent has terminated; it is adopted by init (PID 1 / systemd) which reaps it when it ends.

In short: Zombie = a dead child whose paperwork nobody collected. Orphan = a living child whose parent died first.

Think about it

Output-prediction and definition questions on zombie vs orphan are standard in GATE and interviews, and zombies are a real source of PID leaks.

When a process calls exit(), the kernel frees its memory and open files but keeps a small PCB entry (PID, exit status, resource usage) so that the parent can retrieve it with wait()/waitpid(); the child is in the Zombie (Terminated) state until then.

A zombie consumes no CPU or memory except a process-table slot; many zombies can exhaust PIDs.

A zombie cannot be killed with kill -9 because it is already dead; fix by making the parent call wait(), handle SIGCHLD, or terminate the parent so init adopts and reaps the zombies.

If the parent exits first, its children become orphans and are re-parented to init, which regularly calls wait() so orphans never become permanent zombies.

Daemons are deliberately orphaned (double fork) to detach from the terminal.

Comparison

Zombie — terminated, parent alive and not waiting, appears as Z/defunct in ps; Orphan — alive, parent dead, adopted by init, PPID becomes 1.

Prevention in code: wait(NULL) in the parent, or signal(SIGCHLD, SIG_IGN), or a SIGCHLD handler with waitpid(-1, NULL, WNOHANG).

Terminating a parent with live children under cascading termination (some OSs) kills the children too — Unix does not do this by default.

Key points

  • Zombie: Terminated process whose exit status is not yet collected by the parent.
  • Orphan: Running process whose parent has terminated first; adopted by init.
  • SIGCHLD: Signal sent to a parent when a child terminates.
  • Reaping: Parent collecting child exit status via wait()/waitpid(), freeing the PCB entry.
  • Zombie → terminated, parent alive; Orphan → running, parent dead.
  • GATE trap: kill -9 cannot remove a zombie; only reaping (or killing the parent) does.

Example

Code
Creating a zombie and an orphan:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void) {
    pid_t pid = fork();
    if (pid == 0) {                 // child
        printf("child %d exits\n", getpid());
        exit(0);                    // child becomes ZOMBIE until parent waits
    } else {                        // parent
        sleep(30);                  // during this time: ps shows child as <defunct>
        // wait(NULL);              // uncomment to reap the zombie
    }
    return 0;
}
/* Orphan: make the parent exit first while child still sleeps:
   if (pid > 0) exit(0); else { sleep(10); printf("ppid=%d\n", getppid()); }  -> ppid=1 */
4

Context Switching Mechanics

A context switch saves the state of the running process in its PCB and loads the saved state of another process so the CPU can run it.

In short: Bookmark one process, load another’s bookmark, and continue.

Think about it

It is the price paid for multitasking and a key factor in choosing time quanta.

Saved/restored

program counter, CPU registers, stack pointer, memory-management registers (page-table base), and process state.

Context-switch time is pure overhead: no useful work happens, and it also hurts caches and the TLB (unless entries are tagged with address-space IDs).

Switching between threads of the same process is cheaper since the address space is shared and no page-table switch or TLB flush is needed.

Hardware features such as multiple register sets reduce the time.

Too small a time quantum increases the number of switches and wastes CPU.

Key points

  • Context: CPU registers, PC and memory-management state of a process.
  • Overhead: Time spent on switching rather than running user code.
  • CPU utilization = useful time / (useful time + switch time). If quantum is q and switch time is s, utilization ≈ q/(q+s).
5

Process vs Thread

A thread is the basic unit of CPU utilization inside a process. Threads of one process share code, data, heap and open files but each has its own program counter, registers and stack.

In short: Processes are separate houses; threads are people living in the same house, sharing the kitchen but each with their own bed.

NEW Admitted READY Scheduler Dispatch Interrupt / Time Slice RUNNING Exit TERMINATED WAITING / I/O
Process & Thread Management

Think about it

Concurrency inside one application without the cost of many full processes.

Benefits

responsiveness, resource sharing, economy (creation and switching much cheaper than for processes), and scalability on multicore CPUs.

Risk

  • 1because memory is shared, threads need synchronization
  • 2one faulty thread can crash the whole process.

Processes are isolated and communicate via IPC (pipes, message queues, shared memory); threads communicate through shared variables.

Thread-private: stack, registers, PC, thread ID, errno.

Shared: code, global data, heap, open files, signal handlers.

Key points

  • TCB: Thread control block holding thread-specific state.
  • Multithreading: Multiple threads of control within one process.
  • Thread pool: Pre-created threads reused to serve tasks.
  • Process switch costs more than thread switch (address-space change, TLB effects).
  • Parallelism needs multiple cores; concurrency can occur on one core by interleaving.
6

Multithreading Models

User-level threads (ULT) are created and scheduled by a user library; the kernel sees only one process. Kernel-level threads (KLT) are managed and scheduled directly by the kernel.

In short: ULT = the app juggles its own tasks, the OS is unaware. KLT = the OS knows and schedules every thread.

Threads share CPU · sync protects data

Think about it

Thread model determines blocking behaviour and parallelism of the application.

ULT: very fast creation and switching (no system call), can use custom scheduling, portable; but if one thread blocks in a system call the entire process blocks, and a process cannot use multiple cores.

KLT: a blocking thread does not block siblings and threads can run in parallel on multiple CPUs, but creation and switching need kernel involvement and are slower.

Mapping models

many-to-one (many ULT to one KLT: blocking blocks all, no parallelism), one-to-one (Linux, Windows: more concurrency, overhead per thread), many-to-many (flexible, complex; two-level model also allows binding).

Key points

  • Many-to-one: Many user threads mapped onto one kernel thread.
  • One-to-one: Each user thread has its own kernel thread.
  • Many-to-many: M user threads multiplexed over N kernel threads (N ≤ M).

Example

Code
POSIX threads sharing a global:
#include <pthread.h>
#include <stdio.h>

int counter = 0;                 // shared among threads
void *work(void *arg) {
    counter++;                   // unsynchronized (race!)
    printf("thread %ld ", (long)arg);
    return NULL;
}
int main(void) {
    pthread_t t[2];
    for (long i = 0; i < 2; i++) pthread_create(&t[i], NULL, work, (void *)i);
    for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
    return 0;
}

Solved examples

Example 01 · Basic

How many total processes (including the original) are created by: fork(); fork(); fork(); ?

Given Data:
    Required To Find:

    Total process count

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: Start with 1 process.
    Step 2: After the first fork: 2 processes.
    Step 3: After the second fork every existing process forks: 4 processes.
    Step 4: After the third fork: 8 processes.
    Final Answer: 8 processes in total, so 7 new child processes.

    Approach note: n unconditional forks give 2^n processes and 2^n - 1 children.

    Example 02 · Intermediate

    Predict how many times "X" is printed: if (fork() == 0) { fork(); } printf("X");

    Given Data:
      Required To Find:

      Number of prints

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: Parent calls fork; this creates child C1. The parent gets a non-zero value and skips the if body.
      Step 2: C1 gets 0, enters the body and forks again, creating C2.
      Step 3: Now three processes exist: the parent, C1 and C2.
      Step 4: Each of them executes printf("X") after the if.
      Final Answer: 3 times.

      Approach note: Trace which processes enter the branch; do not apply 2^n blindly when forks are conditional.

      Example 03 · Intermediate

      A system has a context-switch time of 2 ms and uses a time quantum of 8 ms. What fraction of CPU time is wasted if every quantum is fully used? What if the quantum is 2 ms?

      Given Data:
      • Switch time s = 2 ms
      • Quantum q = 8 ms, then 2 ms
      Required To Find:

      Overhead fraction

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: For q = 8 ms: useful = 8 ms, overhead = 2 ms per cycle of 10 ms.
      Step 2: Overhead = 2 / 10 = 20%.
      Step 3: For q = 2 ms: cycle = 2 + 2 = 4 ms.
      Step 4: Overhead = 2 / 4 = 50%.
      Final Answer: 20% overhead with q = 8 ms; 50% with q = 2 ms.

      Approach note: Shorter quantum improves responsiveness but increases switching overhead.

      Example 04 · Basic

      A process has 3 user-level threads. The process makes a blocking system call. In a pure many-to-one (user-level) threading model, how many threads can keep running?

      Given Data:
        Required To Find:

        Count

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: Many-to-one maps all user threads to one kernel thread
        Step 2: A blocking syscall blocks the kernel thread
        Step 3: All 3 user threads stop
        Final Answer: 0 of the 3 can run (whole process blocks)

        Approach note: One-to-one (kernel threads) allows siblings to continue.

        Real-world applications

        OS

        Using Process & Thread Management in real projects

        Web servers (process or thread per request), shell implementation, multi-threaded apps, and debugging zombie processes.

        Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

        Common mistakes

        ❌ Myth: Threads of a process share everything.

        Why this is wrong: Each thread needs its own stack, registers and PC to run independently.

        ✅ Verified Truth: Threads share code, data, heap and files but not stack or registers.

        ⚠️ Exam Tip: List shared vs private items explicitly in answers.

        ❌ Myth: A process can go directly from Waiting to Running when its I/O completes.

        Why this is wrong: The scheduler must pick it; it first returns to the ready queue.

        ✅ Verified Truth: Correct transition is Waiting → Ready → Running.

        ⚠️ Exam Tip: GATE state-diagram options often include the invalid Waiting→Running edge.

        ❌ Myth: Kernel threads are always better than user threads.

        Why this is wrong: Kernel threads have higher creation and switch cost and need system calls.

        ✅ Verified Truth: Each has trade-offs: ULT are cheap but block entire process; KLT allow parallelism at higher cost.

        ⚠️ Exam Tip: State both pros and cons.

        Revision notes

        A process is a program in execution with its own address space and a PCB; threads are lightweight units of execution inside a process. This chapter covers process states and transitions, the PCB, fork/exec/wait, threads vs processes, user vs kernel threads and context switching cost.

        High-Yield Quick Revision Points

        1. States: New, Ready, Running, Waiting, Terminated; Waiting→Ready not Running
        2. fork returns 0 in child, PID in parent; n forks → 2^n processes
        3. Zombie = finished but not reaped; orphan = parent died
        4. Context switch is pure overhead; overhead ≈ s/(q+s)
        5. Threads share code/data/heap/files; private stack/registers/PC
        6. ULT cheap but block-all; KLT parallel but costlier

        Practice questions

        Question 1 · MCQ (GATE)

        A program executes fork() four times in a row with no conditions. Total processes created including the original?

        Question 2 · MCQ (GATE)

        Which of the following is NOT shared among threads of the same process?

        Question 3 · MCQ (GATE)

        A process whose parent has terminated without waiting is called:

        Question 4 · MCQ (GATE)

        In the many-to-one thread model, if one thread makes a blocking system call:

        Question 5 · MCQ (GATE)

        Which information is saved in the PCB during a context switch?