Operating Systems

The Conductor of
Digital Chaos

An Operating System (OS) is the software that manages computer hardware and software resources. It provides common services for computer programs.

Without it, every application would need to know how to talk to the hard drive, send pixels to the screen, and manage its own memory. The OS abstracts this complexity.

01 / The Core

Kernel vs User Mode

User Mode

Where your apps run (Browser, Word, Games). Restricted access to hardware.

Unprivileged

Kernel Mode

Where the OS core runs. Full access to hardware (CPU, RAM, Disk).

Privileged
The Bridge
System Call (syscall)

Apps ask the Kernel to do things (e.g., "Read File") via System Calls.

02.1 / Execution

Processes & Threads

A Process is a program in execution. A Thread is the smallest unit of execution within a process.

Process Control Block (PCB)

The data structure storing all info about a process.

  • Process ID (PID)
  • Process State (Ready, Run, Wait)
  • CPU Registers (Program Counter)
  • Memory Limits

Context Switching

Saving the state of the old process and loading the state of the new one.

Info: Context switching is pure overhead. The CPU does no "useful" work during the switch.
02.2 / Logic

CPU Scheduling Algorithms

The CPU Scheduler is the part of the OS that decides which process runs next. Its goal is to maximize CPU utilization and throughput while minimizing waiting time.

Preemptive vs Non-Preemptive
  • Non-Preemptive: Once a process starts, it keeps the CPU until it voluntarily releases it (finishes or waits for I/O). (e.g., FCFS, SJF)
  • Preemptive: The OS can interrupt a running process and move it to the ready queue if a higher-priority process arrives. (e.g., SRTF, RR)
Key Metrics
  • Arrival Time (AT): When a process enters the ready queue.
  • Burst Time (BT): Time required by a process to execute.
  • Completion Time (CT): When a process finishes execution.
  • Turnaround Time (TAT): CT - AT (Total time spent in system).
  • Waiting Time (WT): TAT - BT (Total time spent waiting).

CPU Scheduler

Sys_Time: 0 // Status: READY

Job Queue (Planned Arrivals)
No pending jobs
Ready Queue (Memory)
Empty
Completed
Count: 0 View table below
Central Processing Unit
CORE_01 IDLE
-
Gantt Chart (Timeline)
Scale: 20px / unit
Process Metrics
Process Arrival (AT) Burst (BT) Completion (CT) Turnaround (TAT) Waiting (WT)
No data available
System Log
> System Initialized.
02.1 / Deep Dive

Algorithm Analysis

First-Come, First-Served (FCFS)

The simplest scheduling algorithm. Processes are executed in the exact order they arrive in the ready queue. It is non-preemptive, meaning once a process starts, it runs until completion.

Advantages
  • Simple to understand and implement.
  • Fair in the sense that early arrivals are served first.
  • No starvation (every process eventually runs).
Disadvantages
  • Convoy Effect: Short processes stuck waiting behind a long process suffer from high waiting times.
  • Poor average Waiting Time and Turnaround Time.
  • Not suitable for time-sharing systems.

Shortest Job First (SJF)

Selects the process with the smallest execution (burst) time. This version is non-preemptive. If two processes have the same burst time, FCFS is used to break the tie.

Advantages
  • Optimal: Gives the minimum average waiting time for a given set of processes.
  • Maximizes system throughput.
Disadvantages
  • Starvation: Long processes may never run if short processes keep arriving.
  • Impossible to implement in general OS since future burst time is unknown (requires prediction).

Shortest Remaining Time First (SRTF)

The preemptive version of SJF. The OS constantly monitors the ready queue. If a new process arrives with a burst time shorter than the remaining time of the current process, the CPU preempts the current one.

Advantages
  • Even lower average waiting time than non-preemptive SJF.
  • Short jobs are handled very quickly.
Disadvantages
  • High context switching overhead due to frequent preemption.
  • Complex to implement.
  • Subject to starvation of long processes.

Priority Scheduling

Processes are assigned a priority number (in this sim, lower number = higher priority). The CPU is allocated to the process with the highest priority.

Advantages
  • Allows the OS to handle urgent tasks (e.g., system errors, I/O) immediately.
  • Flexible: Can act like FCFS (if priorities equal) or SJF (if priority ~ 1/burst).
Disadvantages
  • Indefinite Blocking (Starvation): Low priority processes may wait forever.
  • Solution: Aging (gradually increasing priority of waiting processes).

Round Robin (RR)

Designed for time-sharing systems. The CPU is assigned to the process for a small time unit called a Time Quantum. Once the quantum expires, the process is preempted and added to the end of the ready queue.

Advantages
  • Fair: Every process gets an equal share of CPU.
  • Responsive: Good for interactive systems; no process waits too long for its first turn.
Disadvantages
  • Performance depends heavily on Quantum size.
  • Small Quantum = High Context Switching overhead.
  • Large Quantum = Degenerates into FCFS.
02.3 / Coordination

Process Synchronization

When multiple processes execute concurrently and share data, they must be synchronized to avoid Race Conditions—where the output depends on the specific order of execution.

The Critical Section Problem

The "Critical Section" is the part of the code where a process accesses shared resources. The goal is to ensure only one process executes in its critical section at a time.

3 Requirements
  • Mutual Exclusion: If one process is in CS, no other can be.
  • Progress: If no one is in CS, selection of the next process cannot be postponed indefinitely.
  • Bounded Waiting: Limit on how many times others can enter CS before a requesting process is granted access.

Peterson's Solution

A classic software-based solution for 2 processes. It uses two shared variables: turn and flag[].

// Process i
flag[i] = true;
turn = j;
while (flag[j] && turn == j);
/* CRITICAL SECTION */
flag[i] = false;
/* REMAINDER SECTION */

Interactive: Mutual Exclusion Demo

Unlocked
Non-Critical
P0
Non-Critical
P1

Synchronization Tools & Problems

Semaphores

A synchronization tool that provides a more sophisticated way (than Mutex locks) for process to synchronize their activities. A semaphore S is an integer variable accessed only through two atomic operations:

wait(S) [P operation] while (S <= 0); // busy wait
S--;
signal(S) [V operation] S++;
Types: Binary Semaphore (0 or 1, same as Mutex) vs Counting Semaphore (unrestricted domain, for resource management).
Bounded-Buffer

(Producer-Consumer): Producers generate data to a specific size buffer. Consumers remove it. Must ensure producer doesn't add to full buffer and consumer doesn't remove from empty one.

Readers-Writers

Multiple readers can read simultaneously. But if a writer is writing, no other process (reader or writer) can access the database. Problem: ensuring no starvation.

Dining Philosophers

5 philosophers sit at a table with 5 chopsticks. Need 2 to eat. Classic deadlock/starvation example if not handled correctly (e.g., using semaphores or monitors).

Deadlocks

A situation where a set of processes are blocked because each process is holding a resource and waiting for another resource acquired by some other process.

Deadlock Characterization

Deadlock can arise if four conditions hold simultaneously (Coffman Conditions):

1. Mutual Exclusion At least one resource must be held in a non-sharable mode.
2. Hold to Wait Process holds at least one resource and is waiting for others.
3. No Preemption Resources cannot be preempted; must be released voluntarily.
4. Circular Wait P0 waits for P1, P1 waits for P2, ..., Pn waits for P0.

Methods for Handling Deadlocks

Deadlock Ignorance (Ostrich Algorithm) Pretend deadlock never occurs. Used by most OS (Unix, Windows) because deadlocks are rare and handling is expensive.
Deadlock Prevention Ensure at least one of the 4 conditions cannot hold.
Deadlock Avoidance OS assesses if allocating a resource will leave the system in a safe state (e.g., Banker's Algorithm).
Deadlock Detection & Recovery Allow deadlock to occur, detect it, and recover.

Deadlock Prevention

  • Mutual Exclusion: Make resources sharable (e.g., Read-only files).
  • Hold and Wait: Process must request all resources before execution.
  • No Preemption: If a process requests a resource that isn't available, preempt all its held resources.
  • Circular Wait: Impose a total ordering of all resource types.

Deadlock Avoidance

Requires the OS to know in advance the maximum resources a process will need.

Banker's Algorithm

Before allocation, check if the system remains in a Safe State (there exists a sequence to satisfy all requests). If unsafe, process must wait.

Deadlock Detection

  • Single Instance: Use a Wait-for Graph. If cycle exists → Deadlock.
  • Multiple Instances: Use algorithm similar to Banker's to track Available, Allocation, and Request matrices.

Recovery from Deadlock

Process Termination: Abort all deadlocked processes OR abort one at a time until cycle breaks.
Resource Preemption: Select a victim, rollback process to safe state, and starve the victim if needed.
03 / Space

Memory Management

Managing RAM. The OS must trick programs into thinking they have continuous, unlimited memory (Virtual Memory).

Background Swapping

When RAM is insufficient, the OS temporarily moves idle processes from memory to a backing store (Disk) and brings them back when needed.

RAM (Full)
→ Swap Out ← Swap In
DISK

Contiguous Memory Allocation

Each process is contained in a single, continuous section of memory.

Fixed Partition

Memory is divided into fixed-size partitions. Leads to Internal Fragmentation (Process smaller than partition).

Variable Partition

OS allocates exactly the size needed. Leads to External Fragmentation (Holes between processes).

Paging

Eliminates external fragmentation by dividing physical memory into fixed-size blocks called Frames and logical memory into blocks of the same size called Pages.

  • Physical Address Space: Non-contiguous.
  • Logical Address Space: Contiguous view for the process.

Structure of Page Table

The data structure used to map Logical Pages to Physical Frames.

Hierarchical: Break table into smaller tables (e.g., Two-Level) to save contiguous RAM.
Hashed: Use hash map for large address spaces (> 32-bit).
Inverted: One entry per Physical Frame instead of per Logical Page. Saves memory.

Segmentation

Supports the user view of memory. A program is a collection of segments rather than a linear stream of bytes.

Main()
Stack
Heap
Global Vars

Virtual to Physical Address Translator

Page 0-> Frame 5
Page 1-> Frame 2
Page 2-> Frame 8
Page 3-> Frame 1
Virtual Addr = Page + Offset
-

Virtual Memory Management

Technique that separates user logical memory from physical memory, allowing execution of processes not completely in memory.

Demand Paging

Pages are loaded into RAM only when they are needed during execution.

Page Hit: Page is in RAM.
Page Fault: Page not in RAM → Trap OS → Read Disk.

Copy-on-Write (CoW)

Parent and Child processes share the same pages initially. If either writes to a page, a copy is made.

Proc A
→ Shared ←
Proc B

Allocation of Frames

How to distribute fixed RAM frames among processes?

  • Equal: Every process gets same number of frames.
  • Proportional: Frames allocated based on process size.
  • Global vs Local: Can a process steal a frame from another?

Thrashing Critical

System spends more time paging (I/O) than executing. CPU utilization drops effectively to zero.

Disk I/O (Paging) 99%
CPU Usage 1%

Page Replacement Simulator

When a Page Fault occurs and memory is full, the OS must choose a "victim" frame to replace.
Algorithms: FIFO (First-In-First-Out), LRU (Least Recently Used), Optimal (Replace page needed furthest in future).

Hit Fault
FIFO First-In First-Out

The oldest page in memory is selected for replacement. It treats memory like a queue.

  • Pros: Simple to understand and implement. Low overhead.
  • Cons: Suffers from Belady's Anomaly (increasing frames can increase faults).
  • Best for: Simple systems where performance is not critical.
LRU Least Recently Used

Replaces the page that has not been used for the longest period of time. Assumes recent past predicts near future.

  • Pros: Good approximation of Optimal. No Belady's Anomaly.
  • Cons: Requires hardware support (timestamp/counter). High overhead.
  • Best for: General purpose systems (industry standard).
Optimal Theoretical

Replaces the page that will not be used for the longest period of time in the future.

  • Pros: Lowest possible page-fault rate. Used as a benchmark.
  • Cons: Impossible to implement in real-time (requires future knowledge).
  • Use: To measure how well other algorithms perform.
04 / Persistence

File Systems

How data is stored and retrieved. The OS organizes bytes into Files and Directories.

Method Structure Pros/Cons
Contiguous File stored in continuous blocks. Fast read, but hard to grow files.
Linked Blocks point to next block (Linked List). No fragmentation, but slow random access.
Indexed (inodes) Index block holds pointers to all data blocks. Best of both. Used in Unix/Linux.
05 / Glossary

Key Terms

Essential terminology for understanding Operating Systems.

Kernel

The core component of the OS that has complete control over everything in the system. It manages resources and communicates with hardware.

Process

A program in execution. It includes the program code, current activity (program counter), stack, data, and heap.

Thread

The smallest unit of processing that can be scheduled by an OS. A process can have multiple threads sharing the same resources.

Deadlock

A situation where a set of processes are blocked because each process is holding a resource and waiting for another resource acquired by some other process.

Semaphore

A synchronization object (integer variable) used to control access to a common resource by multiple processes in a concurrent system.

Mutex

Short for Mutual Exclusion. A locking mechanism that ensures only one thread can acquire the lock/enter a critical section at a time.

Paging

A memory management scheme that eliminates external fragmentation by allowing a process's physical address space to be non-contiguous.

Virtual Memory

A technique that allows the execution of processes that are not completely in memory, creating an illusion of a very large main memory.

Context Switch

The process of storing the state of a process or thread, so that it can be restored and resume execution from the same point later.

System Call

The programmatic way in which a computer program requests a service from the kernel of the operating system it is executed on.

06 / Knowledge Check

Knowledge Check

Verify your understanding of Operating Systems. Pass the exam with a perfect score to earn your completion certificate.