intview Operating Systems

1. Introduction to Operating Systems

What is an Operating System?

An Operating System is system software that acts as an interface between the user or application programs and the computer hardware. It manages and allocates system resources such as CPU, memory, storage, and I/O devices among different programs. It also provides a platform or environment in which application programs can run efficiently and securely.

Examples of Operating Systems

  • Windows (Microsoft)
  • Ubuntu (Linux distribution)
  • Debian (Linux distribution)
  • Fedora (Linux distribution)
  • macOS (Apple)
  • Android (Google)
  • iOS (Apple)
  • ChromeOS (Google)
  • Tizen (Samsung)
  • Unix (Multi-user operating system)

Is Linux an Operating System?

Linux technically refers to the kernel. Operating systems such as Ubuntu and Debian use the Linux kernel along with other system software. So Ubuntu is a Linux distribution, while Linux itself is the kernel.

Goals of Operating System

Primary Goals:

  • Convenience: Make the computer easy and convenient for users.
  • Efficiency: Utilize hardware resources efficiently.

Secondary Goals:

  • Security: Protect data and system resources.
  • Reliability: Ensure stable and error-free operation.
  • Scalability: Support increasing users, processes, and resources.
  • Maintainability: Make the system easy to update and manage.

Functions of Operating System

  1. Process Management: Creates, schedules, and terminates processes.
  2. Memory Management: Allocates and deallocates memory to processes.
  3. I/O Management: Manages input/output devices like keyboard, disk, and printer.
  4. File Management: Creates, organizes, stores, and manages files and permissions.
  5. Network Management: Manages network connections and data communication.
  6. Security & Protection: Protects the system through authentication and access control.

Types of Operating Systems

1. Batch Operating System

“A Batch OS executes a group of jobs in batches without user interaction. Jobs with similar requirements are grouped together and executed sequentially.”

Example: Payroll processing, bank statement generation.

Key point: No direct user interaction.

2. Multiprogramming Operating System

“A multiprogramming OS keeps multiple programs in memory at the same time and switches the CPU to another program when one is waiting for I/O, improving CPU utilization.”

Key point: Multiple programs in memory → better CPU utilization.

3. Multitasking Operating System

“A multitasking OS allows multiple tasks or applications to appear to run simultaneously by rapidly switching the CPU between them.”

Example: Listening to music while browsing and downloading a file.

Key point: Multiple tasks at the same time.

4. Time-Sharing Operating System

Time-Sharing is a specific form of multitasking that supports multiple users on the same computer system.

“A time-sharing OS gives each process or user a small time slice of CPU time, allowing multiple users or processes to interact with the system simultaneously.”

Key point: CPU time is divided into time slices.

5. Multiprocessing Operating System

“A multiprocessing OS uses two or more CPUs or processor cores to execute processes in parallel, improving performance and reliability.”

Key point: Multiple processors → parallel execution.

6. Distributed Operating System

“A distributed OS manages multiple connected computers and makes them appear to users as a single unified system.”

Key point: Multiple computers → single system view.

7. Network Operating System

“A Network OS is designed to manage and provide services over a network, such as file sharing, printer sharing, and user management.”

Examples: Windows Server, Linux server distributions.

Key point: Provides network-based services.

8. Real-Time Operating System (RTOS)

“A real-time OS guarantees that tasks are completed within a specified time constraint. It is commonly used where timing is critical.”

Hard Real-Time

“Missing a deadline is unacceptable and can cause system failure.”

Examples: Aircraft control systems, medical critical systems.

Soft Real-Time

“Missing an occasional deadline is acceptable, but it may reduce system performance.”

Examples: Video streaming, online gaming.

Key point: Hard = deadline must be met; Soft = occasional delay is acceptable.

9. Mobile Operating System

“A Mobile OS is designed specifically for smartphones and tablets, providing features such as touch interaction, mobile networking, power management, and app management.”

Examples: Android, iOS.

Key point: Designed for mobile devices.

Quick Revision

TypeMain Idea
BatchJobs processed in batches
MultiprogrammingMultiple programs in memory
MultitaskingMultiple tasks appear to run together
Time-sharingCPU divided into time slices
MultiprocessingMultiple CPUs/cores
DistributedMultiple computers work as one system
NetworkProvides network services
Real-TimeTasks must meet deadlines
MobileDesigned for mobile devices

Multiprogramming vs Multitasking vs Time-Sharing vs Multiprocessing

FeatureMultiprogrammingMultitaskingTime-SharingMultiprocessing
Core IdeaMultiple programs kept in memoryMultiple tasks run seemingly at onceCPU time shared among users/tasksMultiple CPUs/cores work together
How it worksIf one program waits for I/ O, CPU switches to anotherCPU rapidly switches between tasks using time slicesEach task/user gets a fixed time quantumDifferent CPUs/cores execute tasks in parallel
Main GoalMaximize CPU utilization and throughputProvide smooth user interactionFair CPU sharing and quick responseIncrease performance and reliability
Processor CountSingle CPUSingle CPUSingle CPUMultiple CPUs/cores
ExecutionOne process at a time on CPURapid switchingTime-quantum based switchingTrue parallel execution
ExampleRunning multiple programs in memoryBrowser + music + editorMultiple users accessing a serverMulti-core computer running tasks in parallel

Easy Way to Remember

  • Multiprogramming → Keep multiple programs in memory.
  • Multitasking → Run multiple tasks seemingly simultaneously.
  • Time-sharing → Share CPU time fairly using time slices.
  • Multiprocessing → Use multiple CPUs/cores for parallel execution.

Importance of Operating System

  • Manages Resources: CPU, memory, storage, and I/O devices.
  • Runs Applications: Provides an environment for programs to execute.
  • Provides Security: Protects data and system resources.
  • User Interface: Provides CLI/GUI for user interaction.
  • Ensures Efficiency: Improves resource utilization and system performance.
  • Handles Errors: Detects and manages system errors.

OS Interface

Interview-ready answer:

“An OS interface is the way through which a user or application interacts with the operating system to perform tasks.”

Types of OS Interface

InterfaceDescriptionExample
CLIUser interacts using commandsLinux Terminal, Command Prompt
GUIUser interacts using windows, icons, menus, etc.Windows, macOS
System Call InterfaceApplications interact with OS services through system callsopen(), read(), write()

Easy to Remember

User → Interface → OS → Hardware

2. Operating System Architecture & The Kernel

What is Kernel?

The kernel is the core component of an operating system. It acts as a bridge between applications and hardware and manages important resources such as CPU, memory, processes, and I/O devices.

Is the Kernel the Same as the Operating System?

“No. The kernel is the core part of the operating system, while an operating system also includes other components such as system utilities, libraries, drivers, and user interfaces.”

User Mode and Kernel Mode

Modern operating systems use two execution modes to protect the system:

1. User Mode

  • Used by normal applications like Chrome, VS Code, etc.
  • Has limited access to hardware and system resources.
  • Cannot directly execute privileged instructions.
  • If an application needs OS services, it uses a system call.

2. Kernel Mode

  • Used by the OS kernel.
  • Has full access to hardware and system resources.
  • Can execute privileged instructions.
  • Handles tasks like memory management, process scheduling, and device management.

Mode Bit

“A mode bit is a hardware flag used by the CPU to indicate whether the current process is running in user mode or kernel mode.”

Typically:

  • Mode bit = 1 → User Mode
  • Mode bit = 0 → Kernel Mode

Does Kernel Run All the Time?

“The kernel is always present in memory while the operating system is running, but it does not continuously execute. The CPU runs kernel code when it needs to perform OS-related tasks, such as handling system calls, interrupts, process scheduling, or hardware operations. Otherwise, the CPU can execute user-level programs.”

Functions of Kernel

  • Process Management: Creates, schedules, and terminates processes.
  • Memory Management: Allocates and manages memory.
  • Device Management: Controls hardware devices.
  • File Management: Handles file and storage operations.
  • Inter-Process Communication (IPC): Enables processes to communicate and share data.
  • System Calls: Provides OS services to applications.
  • Security & Protection: Controls access to system resources.

Types of Kernel

There are mainly 5 types of kernels:

1. Monolithic Kernel

  • All major OS services run in kernel space.
  • Fast but less isolated.
  • Example: Linux, Unix.

2. Microkernel

  • Only essential services run in kernel space.
  • Other services run in user space.
  • More secure and modular but may have performance overhead.
  • Example: MINIX, QNX.

3. Hybrid Kernel

  • Combines features of monolithic and microkernel designs.
  • Example: Windows NT, macOS (XNU).

4. Exokernel

  • Provides very low-level hardware access to applications.
  • Gives applications more control over resources.
  • Example: MIT Exokernel.

5. Nano Kernel

  • Provides an extremely small set of basic hardware-level functions.
  • Focuses on minimalism and efficiency.

What is an Interrupt?

An interrupt is a signal sent to the CPU/Kernal by hardware or software to indicate that an event needs immediate attention. The CPU temporarily pauses its current execution, handles the interrupt through the operating system, and then resumes the previous task.

Types of Interrupts

Hardware Interrupt

  • Generated by hardware devices.
  • Example: Keyboard input, mouse click, network packet.

Software Interrupt

  • Generated by software/programs.
  • Example: System calls or software-generated exceptions.

How an Interrupt Works

Event → Interrupt → CPU pauses current task → Kernel handles it → CPU resumes task

What is a System Call?

“A system call is a mechanism through which a user-level application requests a service from the operating system kernel. Since applications cannot directly access privileged resources, they use system calls to request services such as file operations, process creation, memory management, and device access.”

Why are System Calls Needed?

Applications run in user mode, while sensitive OS operations require kernel mode.

Common Types of System Calls

  • Process Management: fork(), exec(), exit()
  • File Management: open(), read(), write(), close()
  • Memory Management: mmap(), brk()
  • Device Management: Device read/write operations
  • Interprocess Communication: Pipes, shared memory, sockets
  • Protection: Access control and permissions

How Do System Calls Work?

“A system call provides a controlled way for a user program to request a service from the OS kernel.”

Steps:

  1. System Call: Program requests an OS service.
  2. Mode Switch: CPU switches from User Mode → Kernel Mode.
  3. Identify Call: Kernel identifies the system call using its system call number.
  4. Execute: Kernel performs the requested operation.
  5. Return Result: Kernel returns the result to the program.
  6. Mode Switch: CPU switches back from Kernel Mode → User Mode.

System Call Flow

User Program → System Call → Kernel Mode → Kernel executes → Result → User Mode

What Happens When We Turn On a Computer?

When we turn on a computer, the system goes through a booting process. First, the hardware is powered on and the firmware performs a hardware check. Then the bootloader is loaded, which loads the operating system kernel into memory. The kernel initializes hardware, memory, processes, and other OS components. Finally, the system starts the login screen or desktop environment.

Steps

  1. Power On – CPU starts executing firmware instructions.
  2. POST – BIOS/UEFI checks essential hardware.
  3. Bootloader Loads – Firmware finds and loads the bootloader.
  4. Kernel Loads – Bootloader loads the OS kernel into RAM.
  5. Kernel Initialization – Kernel initializes CPU, memory, devices, drivers, etc.
  6. System Services Start – Required OS services and background processes start.
  7. Login/Desktop – User gets the login screen or desktop.

Easy Flow

Power ON → BIOS/UEFI → POST → Bootloader → Kernel → OS Services → Login/Desktop

BIOS Full Form

BIOS = Basic Input/Output System

It is firmware stored on the motherboard that initializes hardware and starts the booting process.

Structure of Operating System

OS structure defines how the components of an operating system are organized and interact with each other.

1. Simple Structure

  • No well-defined structure between OS components.
  • Components can directly interact with each other.
  • Example: Early MS-DOS.
  • Advantage: Simple and fast.
  • Disadvantage: Difficult to maintain and secure.

2. Monolithic Structure

  • All major OS services run in kernel space.
  • Components can directly communicate with each other.
  • Example: Linux, Unix.
  • Advantage: High performance.
  • Disadvantage: A bug in one component can affect the entire kernel.

3. Layered Structure

  • OS is divided into multiple layers.
  • Each layer uses services provided by the layer below it.
  • Advantage: Easy to design, debug, and maintain.
  • Disadvantage: Can introduce performance overhead.

4. Microkernel Structure

  • Only essential services run in the kernel.
  • Other services such as drivers and file systems run in user space.
  • Example: MINIX, QNX.
  • Advantage: Better security and reliability.
  • Disadvantage: Communication between components can add overhead.

5. Modular Structure

  • Kernel is divided into modules.
  • Modules can be dynamically loaded or removed when needed.
  • Example: Linux supports loadable kernel modules.
  • Advantage: Flexible and easier to extend.

6. Hybrid Structure

  • Combines features of monolithic and microkernel approaches.
  • Provides performance while maintaining some modularity.
  • Examples: Windows NT, macOS XNU.

7. Solaris Structure

  • Oracle Solaris uses a modular architecture with a core kernel and dynamically loadable modules.
  • It combines features such as monolithic kernel performance and modular design.

Quick Interview Revision

Simple → Monolithic → Layered → Microkernel → Modular → Hybrid → Solaris

The most important comparison to remember:

Monolithic = everything in kernel space Microkernel = minimum in kernel space Layered = organized into layers Modular = components can be dynamically added/removed Hybrid = combination of approaches

3. Process Management & Inter-Process Communication

What is a Process?

“A process is a program that is currently in execution. It is an active entity that has its own memory, CPU state, resources, and execution context.”

Program vs Process

  • Program: Passive set of instructions stored on disk.
  • Process: Active instance of a program running in memory.

“A program is a passive entity containing a set of instructions stored on secondary storage, such as an executable file. It becomes a process when the executable is loaded into main memory and the operating system creates its PCB. A process is an active entity that requires resources such as CPU time, memory, and registers for execution.

Key Points

  • Program → Passive entity
    • Stored on secondary storage.
    • Contains instructions.
    • Does not require CPU or memory for execution.
  • Process → Active entity
    • Program loaded into main memory.
    • Has a PCB (Process Control Block).
    • Requires CPU, memory, registers, and other resources.
  • Same Program ≠ Same Process
    • Multiple instances of the same program can create separate processes.
    • They have separate execution states and memory such as stack, heap, and data.

Example:

“If I open multiple instances of a browser, each running instance can be represented as a separate process, even though they may share the same program code.”

AspectProgramProcess
Nature / DefinitionPassive entity; static set of instructionsActive entity; execution of a program
StateStored on disk; no active execution stateDynamic states: New, Ready, Running, Waiting, Terminated
ExistenceExists as a file on diskExists temporarily during execution
MemoryTakes storage space on diskUses RAM, CPU, registers, etc.
IdentifierNo unique identifier requiredHas a unique PID (Process ID)

Memory Layout of a Process

“The memory layout of a process describes how a process is organized in main memory during execution.”

A process is typically divided into these sections:

1. Text / Code

  • Contains the program's executable instructions.
  • Usually read-only.

2. Data

  • Contains global and static variables.
  • Divided into initialized and uninitialized data.

3. Heap

  • Used for dynamic memory allocation.
  • Grows/shrinks during execution.
  • Example: new, malloc().

4. Stack

  • Stores function calls, local variables, parameters, and return addresses.
  • Automatically managed during function execution.
Memory Layout of a Process

Attributes of a Process

The attributes of a process are the information the OS maintains to manage and control a process.

These attributes are stored in a structure called the Process Control Block (PCB) (sometimes called a task control block).

  • Process ID (PID): Unique identifier of the process.
  • Process State: Current state such as New, Ready, Running, Waiting, or Terminated.
  • Program Counter: Address of the next instruction to execute.
  • CPU Registers: Stores the current CPU state of the process.
  • CPU Scheduling Information: Priority and scheduling-related information.
  • Memory Information: Details about the memory allocated to the process.
  • I/O Information: Information about files and I/O devices used by the process.
  • Accounting Information: CPU usage, execution time, and other resource usage.

Does a Running Process Access Its PCB from Main Memory?

“The PCB is maintained and managed by the operating system in kernel memory. A process does not directly access its own PCB. The kernel accesses and updates the PCB whenever it needs to manage the process.

Process Control Block (PCB)

“A Process Control Block, or PCB, is a data structure maintained by the operating system that stores all important information about a process. The OS uses the PCB to manage, schedule, and track the process.

What does PCB contain?

  • Process ID (PID): Unique identifier of the process.
  • Process State: New, Ready, Running, Waiting, or Terminated.
  • Program Counter: Address of the next instruction to execute.
  • CPU Registers: Stores the CPU state of the process.
  • Scheduling Information: Priority, scheduling queue information, etc.
  • Memory Management Information: Memory allocated to the process.
  • I/O Information: Files and I/O devices used by the process.
  • Accounting Information: CPU time and other resource usage.

Why is PCB important?

“PCB allows the OS to stop, resume, and manage processes. It is especially important during context switching, because the OS saves the state of one process in its PCB and restores the state of another process from its PCB.”

Process Table

“A Process Table is a data structure maintained by the operating system that contains information about all the active processes in the system. Each entry in the process table typically points to or contains the PCB of a process

Key Points

  • Contains one entry for each process.
  • Stores or references the process's PCB.
  • Helps the OS track and manage processes.
  • Used during process scheduling, context switching, and resource management.
Key Points

Process Management

“Process management is an operating system function responsible for creating, scheduling, executing, synchronizing, and terminating processes. It ensures that processes get the required CPU and other resources efficiently

Main Functions of process management

  • Process Creation: Creates new processes.
  • Process Scheduling: Decides which process gets the CPU.
  • Context Switching: Switches CPU between processes.
  • Process Synchronization: Coordinates processes sharing resources.
  • IPC: Enables processes to communicate and exchange data.
  • Resource Allocation: Allocates CPU, memory, and I/O resources.
  • Process Termination: Terminates completed or failed processes.
  • Deadlock Handling: Detects, prevents, avoids, or recovers from deadlocks.

Inter-Process Communication (IPC)

“Inter-Process Communication, or IPC, is a mechanism provided by the operating system that allows processes to communicate and exchange data with each other.

Why is IPC Needed?

Processes normally have separate memory spaces, so one process cannot directly access another process's memory. IPC provides controlled ways for them to share data and coordinate their execution.

Main IPC Methods

  1. Shared Memory
    • Processes share a common memory region.
    • Very fast because data doesn't need to be repeatedly copied.
    • Requires synchronization to avoid race conditions.
Main IPC Methods
  1. Message Passing
    • Processes communicate by sending and receiving messages.
    • Safer and easier to manage than shared memory.
    • Can be implemented using pipes, message queues, sockets, etc.
Main IPC Methods

IPC Mechanisms

The main IPC mechanisms are:

  1. Pipes
    • Used for communication between processes.
    • Commonly used between related processes.
    • Example: ls | grep txt
  2. Named Pipes (FIFO)
    • Similar to pipes but can be used by unrelated processes.
  3. Message Queues
    • Processes communicate by sending and receiving messages through a queue.
  4. Shared Memory
    • Multiple processes share a memory region.
    • Fastest IPC mechanism, but requires synchronization.
  5. Semaphores
    • Used mainly for process synchronization and controlling access to shared resources.
    • Not primarily used to transfer data.
  6. Sockets
    • Allow processes to communicate locally or over a network.
    • Common in client-server applications.
  7. Signals
    • Used to notify a process that a particular event has occurred.
    • Example: SIGKILL, SIGINT.

Context Switching

“Context switching is the process of saving the state of a currently running process and loading the saved state of another process, so the CPU can switch between them.”

How it works

  1. Current process is running.
  2. An interrupt, system call, or scheduler decision occurs.
  3. OS saves the current process's CPU state in its PCB.
  4. OS selects another process.
  5. OS loads the new process's saved state from its PCB.
  6. CPU resumes execution of the new process.

What is saved?

The context can include:

  • Program Counter
  • CPU Registers
  • Process State
  • Other CPU execution information

Process States

A process state represents the current status of a process during its lifecycle.

The 5 basic process states are:

  1. New
    • Process is being created.
  2. Ready
    • Process is ready to run but waiting for CPU allocation.
  3. Running
    • Process is currently executing on the CPU.
  4. Waiting / Blocked
    • Process is waiting for an event, usually I/O completion.
  5. Terminated
    • Process has finished execution or has been terminated.
Process States

Seven-State Process Model

The seven-state process model extends the basic five-state model by adding two suspended states. These states are useful when a process is temporarily moved from main memory to secondary storage.

7 Process States

  1. New
    • Process is being created.
  2. Ready
    • Process is in memory and waiting for CPU.
  3. Running
    • Process is currently executing.
  4. Blocked / Waiting
    • Process is waiting for an event or I/O.
  5. Terminated
    • Process has completed or been terminated.
  6. Ready Suspended
    • Process is ready to execute but has been moved from main memory to secondary storage.
  7. Blocked Suspended
    • Process is waiting for an event and has been moved from main memory to secondary storage.

Important Transitions

  • Ready → Ready Suspended: Process is swapped out of memory.
  • Ready Suspended → Ready: Process is brought back into memory.
  • Blocked → Blocked Suspended: Blocked process is swapped out.
  • Blocked Suspended → Blocked: Process is brought back while still waiting.
  • Blocked Suspended → Ready Suspended: The event it was waiting for occurs while it is suspended.
Important Transitions

CPU-Bound Process (CPU-Intensive)

“A CPU-bound process spends most of its time performing CPU computations and requires very little I/O.”

  • Requires more CPU time.
  • Performs heavy calculations.
  • I/O operations are relatively less frequent.
  • Example: Video encoding, mathematical calculations, scientific simulations.

I/O-Bound Process (I/O-Intensive)

“An I/O-bound process spends most of its time waiting for I/O operations and requires relatively less CPU computation.”

  • Requires more I/O operations.
  • Frequently waits for disk, network, keyboard, etc.
  • CPU bursts are usually shorter.
  • Example: File copying, database queries, web server requests.

Easy way to remember:

CPU-Bound → More CPU work, less waiting I/O-Bound → More I/O waiting, less CPU work

Types of Processes

Processes can be classified based on their behavior, relationship, and purpose.

  1. CPU-Bound Process
    • Spends most of its time using the CPU.
    • Example: Video encoding, complex calculations.
  2. I/O-Bound Process
    • Spends most of its time waiting for I/O.
    • Example: File or network operations.
  3. Parent Process
    • A process that creates another process.
    • The newly created process is called its child.
  4. Child Process
    • A process created by another process (parent).
  5. Independent Process
    • Does not affect or depend on other processes.
    • Does not share data/state with other processes.
  6. Cooperating Process
    • Can affect or be affected by other processes.
    • Communicates using IPC and may share data.
  7. Zombie Process
    • A process that has finished execution but still has an entry in the process table because its parent has not yet collected its exit status.
  8. Orphan Process
    • A process whose parent has terminated while the child is still running.
    • It is adopted by another system process.
  9. Daemon Process
    • A background process that provides services without direct user interaction.
    • Example: Web server, logging service.

10. Swapper Process

  • A system process responsible for swapping processes between main memory and secondary storage.
  • Helps manage memory under certain OS designs.

Important Interview Differences

Zombie vs Orphan:

Zombie → Child has finished, parent hasn't collected its status. Orphan → Parent has finished, child is still running.

Independent vs Cooperating:

Independent → Doesn't interact with other processes. Cooperating → Communicates/interacts with other processes.

Schedulers

Schedulers are components of an operating system that decide which process should be executed by the CPU at a given time.

Schedulers

“A scheduler is an OS component that decides which processes should be admitted to the system, kept in memory, or given the CPU.”

There are three main types of schedulers:

1. Long-Term Scheduler (Job Scheduler)

  • Selects processes from the job pool waiting on the disk(secondary storage) and loads them into main memory(ready queue).
  • Controls the degree of multiprogramming.
  • Runs relatively infrequently.

2. Short-Term Scheduler (CPU Scheduler)

  • Selects a process from the Ready Queue and assigns the CPU.
  • Short-term scheduler will decide which process is to be executed next and then it will call the dispatcher. A dispatcher is a software that moves the process from ready to run and vice versa. In other words, it is context switching.
  • Runs very frequently, so it must be fast.

3. Medium-Term Scheduler

  • Temporarily removes processes from memory (swap out) and later brings them back (swap in).
  • Helps manage memory and degree of multiprogramming.
  • The swapping is done to reduce degree of multiprogramming

Easy Interview Trick

Long-Term → Selects jobs Medium-Term → Swaps processes Short-Term → Selects CPU process

Flow:

Job Pool → Long-Term Scheduler → Ready Queue → Short-Term Scheduler → CPU

Medium-Term Scheduler: can move processes Memory ↔ Secondary Storage.

Easy Interview Trick

Scheduling Queues

“Scheduling queues are queues maintained by the operating system to keep track of processes waiting for different resources.”

1. Job Queue

  • Contains all processes in the system.
  • Managed mainly by the Long-Term Scheduler.
  • Processes wait here before being admitted to memory.

2. Ready Queue

  • Contains processes that are in main memory and ready to execute.
  • They wait for CPU allocation.
  • Managed by the Short-Term Scheduler.

3. Device / Waiting Queue

  • Contains processes waiting for an I/O device or event.
  • Example: A process waiting for disk I/O.
3. Device / Waiting Queue

Dispatcher

“The dispatcher is an OS component that gives control of the CPU to the process selected by the short-term scheduler.”

In other words, the dispatcher is the module that performs the actual context switching and process execution.

Main Functions

  1. Context Switching: Saves the current process state and loads the selected process state.
  2. Switch to User Mode: Changes CPU from kernel mode to user mode when required.
  3. Jump to Correct Location: Transfers control to the selected process's next instruction.

Scheduler vs Dispatcher

  • Scheduler: Decides which process should run.
  • Dispatcher: Actually gives the CPU to that process.

Dispatch Latency

“Dispatch latency is the time taken by the dispatcher to stop one process and start executing another process.”

It includes the time taken for:

o Saving the state of the current process.

o Loading the state of the new process.

o Performing context switching.

Context Switching

“Context switching is the process in which the OS saves the state of the currently running process and restores the state of another process, allowing the CPU to switch between processes.”

Steps

  1. Save Current Process
    • OS saves the CPU state, such as registers and Program Counter, into the process's PCB.
  2. Select Next Process
    • Short-Term Scheduler selects a process from the Ready Queue.
  3. Restore Next Process
    • OS loads the selected process's saved state from its PCB.
  4. Resume Execution
    • CPU starts executing the selected process from where it was previously stopped.

Degree of Multiprogramming The number of processes that can reside in the ready state at maximum decides the degree of multiprogramming, e.g., if the degree of programming = 100, this means 100 processes can reside in the ready state at maximum.

4. CPU Scheduling & Dispatching

CPU Scheduling

“CPU scheduling is the process by which the operating system selects one process from the ready queue and allocates the CPU to it. The main goal is to use the CPU efficiently and provide good system performance and response time.”

Why is CPU Scheduling Needed?

  • Multiple processes may be ready at the same time.
  • Usually, only one process can use a CPU core at a time.
  • The OS needs to decide which process should run next.

Who Performs It?

  • Short-Term Scheduler: Selects the next process.
  • Dispatcher: Gives the CPU to the selected process.

Types of CPU Scheduling

CPU scheduling is mainly divided into Preemptive and Non-Preemptive scheduling.

1. Non-Preemptive Scheduling

  • Once a process gets the CPU, it keeps it until it finishes or enters the waiting state (e.g., by waiting for I/O) .
  • OS cannot forcibly take the CPU away.
  • Examples: FCFS, SJF, Non-Preemptive Priority.
Types of CPU Scheduling

2. Preemptive Scheduling

  • OS can forcibly take the CPU from a running process and assign it to another process.
  • Useful for multitasking and interactive systems.
  • Examples: Round Robin, SRTF, Preemptive Priority.
Types of CPU Scheduling

Easy Interview Difference

Non-Preemptive → Process gives up CPU voluntarily. Preemptive → OS can take CPU away from the process.

Starvation

“Starvation is a situation where a process waits for an indefinitely long time because other processes keep getting the required resources or CPU before it.”

Example:

In Priority Scheduling, if high-priority processes continuously arrive, a low-priority process may keep waiting and never get CPU time.

Cause

  • Continuous arrival of higher-priority processes.
  • Unfair resource allocation.
  • Poor scheduling policy.

Solution

Aging is the common solution.

“Aging gradually increases the priority of a waiting process so that it eventually gets CPU time.”

Scheduling Criteria

Scheduling criteria are the parameters used to evaluate and compare CPU scheduling algorithms.

  1. CPU Utilization
    • Keep the CPU as busy as possible.
    • Goal: Maximize
  2. Throughput
    • Number of processes completed per unit time.
    • Goal: Maximize
  3. Turnaround Time
    • Total time taken from arrival to completion.
    • Goal: Minimize
  4. Waiting Time
    • Total time a process waits in the ready queue.
    • Goal: Minimize
  5. Response Time
    • Time from request submission until the first response.
    • Goal: Minimize
  6. Fairness
    • Ensure every process gets a reasonable chance to execute.
    • Goal: Avoid starvation

Interview shortcut:

Maximize: CPU Utilization, Throughput Minimize: Turnaround Time, Waiting Time, Response Time Ensure: Fairness

Note: The CPU-scheduling algorithm does not affect the amount of time during which a process executes or perform I/0; it affects only the amount of time that a process spends waiting in the ready queue.

Goodput refer to the number of processes completed per unit time.

Terminologies Used in CPU Scheduling

  1. Arrival Time (AT)
    • Time at which a process enters the Ready Queue.
  2. Burst Time (BT)
    • Total CPU time required by a process for execution.
  3. Completion Time (CT)
    • Time at which a process finishes execution.
  4. Turnaround Time (TAT)
    • Total time taken from arrival to completion.
    • TAT = CT − AT
  5. Waiting Time (WT)
    • Total time a process waits in the Ready Queue.
    • WT = TAT − BT
  6. Response Time (RT)
    • Time from arrival until the process gets CPU for the first time.
    • RT = First CPU Start Time − AT
  7. CPU Burst
    • Continuous period during which a process uses the CPU.
  8. I/O Burst
    • Period during which a process performs or waits for I/O operations.
  9. Time Quantum
    • Fixed CPU time allocated to a process in Round Robin scheduling.

10. Context Switch

  • Switching the CPU from one process to another.

Most Important Formulas

TAT = CT − AT WT = TAT − BT RT = First Start Time − AT

CPU Scheduling Algorithms

CPU scheduling algorithms decide which process from the Ready Queue gets the CPU next.

AlgorithmTypeBasic Idea
FCFSNon-PreemptiveProcess that arrives first gets CPU first
SJFNon-PreemptiveProcess with the shortest burst time runs first
SRTFPreemptiveProcess with the shortest remaining time runs first
LJFNon-PreemptiveProcess with the longest burst time runs first
LRTFPreemptiveProcess with the longest remaining time runs first
Priority SchedulingNon-PreemptiveHighest-priority process runs first
Priority SchedulingPreemptiveHigher-priority process can preempt the current process
Round RobinPreemptiveEach process gets a fixed time quantum in cyclic order
HRRNNon-PreemptiveProcess with the highest response ratio runs first
Multilevel QueueUsually PreemptiveReady queue is divided into multiple separate queues
Multilevel Feedback QueuePreemptiveProcesses can move between queues based on their behavior

Important Formulas

HRRN:

Response Ratio = (Waiting Time + Burst Time) / Burst Time

Easy Interview Revision

  • FCFS → First come, first served
  • SJF → Shortest burst
  • SRTF → Shortest remaining time
  • LJF → Longest burst
  • LRTF → Longest remaining time
  • Priority → Highest priority
  • Round Robin → Fixed time quantum
  • HRRN → Highest response ratio
  • MLQ → Separate fixed queues
  • MLFQ → Processes can move between queues

FCFS (First Come First Serve)

“FCFS is a non-preemptive CPU scheduling algorithm in which the process that arrives first in the ready queue gets the CPU first. Once a process gets the CPU, it runs until it finishes or enters a waiting state.”

How It Works

  • Processes are executed according to their Arrival Time.
  • It follows the FIFO (First In, First Out) principle.
  • It is non-preemptive.
  • Once CPU is allocated, another process cannot forcibly take it.

Convoy Effect

“Convoy effect occurs when a long CPU-bound process holds the CPU for a long time, causing many short processes to wait behind it.”

it results into more average waiting time.

Solution, smaller process has to be executed before longer process, to achieve less average waiting time.

Advantages

  • Simple and easy to implement.
  • Fair based on arrival order.
  • No starvation.

Disadvantages

  • Can cause Convoy Effect.
  • Average waiting time can be high.
  • Poor response time for interactive systems.

SJF (Shortest Job First)

“SJF is a non-preemptive CPU scheduling algorithm in which the process with the shortest CPU burst time is selected first. Once a process starts executing, it continues until it finishes or enters a waiting state.”

How It Works

  • Selects the process with the smallest burst time.
  • It is non-preemptive.
  • If multiple processes have the same burst time, FCFS can be used as a tie-breaker.
  • It generally provides the minimum average waiting time when burst times are known accurately.

Advantages

  • Minimum average waiting time among non-preemptive algorithms under ideal conditions.
  • Better average turnaround time than FCFS in many cases.

Disadvantages

  • Can cause starvation for long processes.
  • CPU burst time must be known or estimated.
  • Not ideal for interactive systems.

Why does SJF give minimum average waiting time?

“Because executing shorter jobs first reduces the amount of time that subsequent processes have to wait.”

SRTF (Shortest Remaining Time First)

“SRTF is the preemptive version of SJF. It always selects the process with the shortest remaining CPU burst time. If a new process arrives with a shorter remaining time than the currently running process, the current process is preempted.”

How It Works

  • It is preemptive.
  • The scheduler continuously considers the remaining burst time.
  • A newly arrived process can preempt the currently running process.
  • If two processes have the same remaining time, FCFS can be used as a tie-breaker.

Advantages

  • Usually gives low average waiting time.
  • Provides good response for short processes.
  • Better than SJF when processes arrive at different times.

Disadvantages

  • Can cause starvation for long processes.
  • More context switching due to preemption.
  • Requires knowledge/estimation of remaining CPU burst time.

SJF vs SRTF

SJF → Non-preemptive → Shortest burst time SRTF → Preemptive → Shortest remaining time

LJF (Longest Job First)

“LJF is a non-preemptive CPU scheduling algorithm in which the process with the longest CPU burst time is selected first. Once the process gets the CPU, it continues until completion or until it enters a waiting state.”

How It Works

  • Selects the process with the largest burst time.
  • Non-preemptive scheduling.
  • If two processes have the same burst time, FCFS can be used as a tie-breaker.

Advantages

  • Simple to implement.
  • Long CPU-intensive processes get priority.

Disadvantages

  • Short processes may suffer long waiting times.
  • Can cause starvation of short processes.
  • Generally poor average waiting and response time.

LRTF (Longest Remaining Time First)

“LRTF is the preemptive version of LJF. It always selects the process with the longest remaining CPU burst time. If a new process has a longer remaining time than the currently running process, the current process is preempted.”

How It Works

  • Preemptive scheduling algorithm.
  • Selects the process with the longest remaining burst time.
  • A newly arrived process can preempt the running process.
  • Scheduling decisions are made whenever a process arrives or the remaining times change.

Advantages

  • Gives preference to long CPU-intensive processes.
  • Can be useful when long jobs should receive CPU priority.

Disadvantages

  • Short processes can suffer starvation.
  • Frequent preemption can cause high context-switching overhead.
  • Generally poor response time for short/interactive processes.

LJF vs LRTF

LJF → Non-preemptive → Longest burst time LRTF → Preemptive → Longest remaining time

Priority Scheduling (Non-Preemptive)

“In non-preemptive priority scheduling, the process with the highest priority is selected from the ready queue and given the CPU. Once it starts executing, it continues until it finishes or enters a waiting state.”

How It Works

  • Each process is assigned a priority.
  • The process with the highest priority runs first.
  • It is non-preemptive, so a running process cannot be forcibly interrupted by a newly arrived higher-priority process.
  • If two processes have the same priority, FCFS can be used as a tie-breaker.

Advantages

  • Simple and flexible.
  • Important/high-priority processes get CPU first.
  • Useful when processes have different levels of importance.

Disadvantages

  • Low-priority processes may suffer starvation.
  • Priority assignment can be difficult.
  • Poor priority design can lead to unfair CPU allocation.

Solution to Starvation

Aging:

“Aging gradually increases the priority of a waiting process so that it eventually gets CPU time.”

Priority Scheduling (Preemptive)

“In preemptive priority scheduling, the process with the highest priority gets the CPU. If a new process arrives with a higher priority than the currently running process, the current process is preempted and the new process gets the CPU.”

How It Works

  • Each process has a priority.
  • The highest-priority process is selected.
  • It is preemptive.
  • A newly arrived higher-priority process can interrupt the running process.
  • If priorities are equal, FCFS can be used as a tie-breaker.

Advantages

  • High-priority processes get quick CPU access.
  • Good for systems where some tasks are more important than others.
  • Provides better response for high-priority processes.

Disadvantages

  • Can cause starvation of low-priority processes.
  • More context switching.
  • Priority assignment must be carefully designed.

Solution to Starvation

Aging:

“Aging gradually increases the priority of processes that have been waiting for a long time.”

Non-Preemptive vs Preemptive Priority

Non-Preemptive → Running process keeps CPU. Preemptive → Higher-priority process can take CPU from running process.

Round Robin (RR)

Interview-ready answer:

“Round Robin is a preemptive CPU scheduling algorithm designed mainly for time-sharing systems. Each process gets a fixed amount of CPU time called a time quantum. After its time quantum expires, the process is preempted and moved to the end of the ready queue.”

How It Works

  1. Processes are placed in the Ready Queue.
  2. Each process gets CPU for a fixed Time Quantum.
  3. If the process finishes → it is removed.
  4. If it doesn't finish → it is preempted and moved to the end of the queue.
  5. The next process gets the CPU.

Advantages

  • Fair: Every process gets CPU time.
  • Good response time.
  • Prevents starvation.
  • Well-suited for time-sharing systems.

Disadvantages

  • Too small time quantum → many context switches and overhead.
  • Too large time quantum → behaves similar to FCFS.
  • Average waiting/turnaround time may be higher than SJF/SRTF.

Important Interview Question

Q: What happens if the time quantum is very large?

“Round Robin approaches FCFS because each process can finish its CPU burst before the scheduler switches to another process.”

Q: What happens if the time quantum is too small?

“There will be frequent context switching, increasing overhead and reducing CPU efficiency.”

Important Interview Question

Multilevel Queue Scheduling

“Multilevel Queue Scheduling divides the ready queue into multiple separate queues based on process type or priority. Each queue can have its own scheduling algorithm, and processes are permanently assigned to a particular queue.”

How It Works

For example, queues may be:

  • System Processes
  • Interactive(Forground) Processes
  • Batch(Background) Processes

Each queue can use a different algorithm:

  • Interactive Queue → Round Robin
  • Batch Queue → FCFS

The OS also needs a method to decide which queue gets the CPU. For example, a higher-priority queue may be served before a lower-priority queue.

Key Characteristics

  • Multiple separate ready queues.
  • Each queue can have a different scheduling algorithm.
  • A process is permanently assigned to one queue.
  • Queues may have different priorities.

Advantage

“It is useful when processes can be clearly divided into different categories.”

Disadvantage

“A process in a lower-priority queue may suffer starvation if higher-priority queues continuously have processes.”

Disadvantage

Multilevel Feedback Queue Scheduling (MLFQ)

Interview-ready answer:

“Multilevel Feedback Queue Scheduling divides the ready queue into multiple queues with different priorities and scheduling algorithms. Unlike Multilevel Queue Scheduling, a process can move between queues based on its CPU usage, priority, or behavior.”

How It Works

  • Multiple queues with different priorities.
  • Higher-priority queues usually get CPU first.
  • Each queue can use a different scheduling algorithm.
  • A process can move between queues.
  • CPU-intensive processes may move to lower-priority queues.
  • Interactive or short processes may remain in higher-priority queues.

Example

Suppose there are three queues:

Q1 → Highest Priority → Round Robin Q2 → Medium Priority → Round Robin Q3 → Lowest Priority → FCFS

A CPU-intensive process may move:

Q1 → Q2 → Q3

while an interactive process may remain in Q1.

Advantages

  • Flexible and adaptive.
  • Good for interactive systems.
  • Gives preference to short and interactive processes.
  • Can reduce starvation when aging or priority boosting is used.

Disadvantages

  • More complex to implement.
  • Requires careful selection of queue priorities and time quantum.
  • Poor configuration can cause starvation or unfairness.

MLQ vs MLFQ

MLQ → Process stays in one queue. MLFQ → Process can move between queues.

MLQ vs MLFQ

5. Process Synchronization & Concurrency Control

Process Synchronization

“Process synchronization is a mechanism used by the operating system to coordinate multiple processes or threads that access shared resources, so that they do not interfere with each other and produce incorrect results.”

Why is Synchronization Needed?

When multiple processes access shared data or resources at the same time, it can lead to a race condition and inconsistent results.

Types of Processes Based on Synchronization

There are two types of processes based on their interaction with other processes:

1. Independent Process

“An independent process does not share data or resources with other processes. Its execution does not affect or get affected by other processes.”

  • No shared data/resources.
  • Does not require process synchronization.
  • Example: Two independent programs performing unrelated calculations.

2. Cooperative Process

“A cooperative process can share data or resources with other processes, so its execution can affect or be affected by other processes.”

  • Shares data or resources.
  • Requires process synchronization.
  • Can communicate using IPC.
  • Example: Producer and Consumer processes sharing a buffer.

Race Condition

“A race condition occurs when multiple processes or threads access and modify shared data concurrently, and the final result depends on the order in which they execute.”

Critical Section

“A critical section is the part of a program where a process or thread accesses or modifies shared resources or shared data. Only one process or thread should execute its critical section at a time when mutual exclusion is required.”

Why is Critical Section Needed?

Without proper synchronization, multiple processes may access shared data simultaneously and cause a race condition.

Structure of a Critical Section

A process generally has four parts:

  1. Entry Section
    • Requests permission to enter the critical section.
    • Example: Acquiring a lock.
  2. Critical Section
    • Accesses or modifies the shared resource.
  3. Exit Section
    • Releases the lock/resource so another process can enter.
  4. Remainder Section
    • Remaining code that does not access the shared resource.
Structure of a Critical Section

Requirements of Critical Section Solutions

A correct critical-section solution should satisfy four requirements:

  1. Mutual Exclusion
    • Only one process can be inside the critical section at a time.
    • Prevents simultaneous access to shared resources.
  2. Progress
    • If no process is in the critical section, a process that wants to enter should be allowed to proceed.
    • The decision should involve only processes that want to enter.
    • No deadlock should occur.
  3. Bounded Waiting
    • A process should not wait indefinitely.
    • There must be a limit on the number of times other processes can enter before a waiting process gets its turn.
    • Prevents starvation.
  4. No Hardware/Software Assumption
    • The solution should not depend on a particular hardware, software, or processor speed.
    • It should work independently of machine speed.

Important Points to Remember

  • Mutual Exclusion: Mandatory requirement.
  • Progress: Mandatory requirement.
  • Bounded Waiting: Not strictly mandatory, but if not satisfied, it can cause starvation.
  • No Hardware/Software Assumption: Not a mandatory condition; a solution may depend on specific hardware/software mechanisms.

Standard Synchronization Problems/Classical IPC Problems

These problems are used to understand process synchronization, mutual exclusion, deadlock, and starvation.

  1. Bounded-Buffer (Producer-Consumer) Problem
    • Producers add data to a fixed-size shared buffer, while consumers remove data.
    • Producer must not add data when the buffer is full.
    • Consumer must not remove data when the buffer is empty.
    • Requires proper synchronization to avoid race conditions.
  2. Readers-Writers Problem
    • Multiple readers can read a shared resource simultaneously.
    • Only one writer can modify the resource at a time.
    • When a writer is active, no reader or other writer can access the resource.
    • Proper priority management is needed to prevent starvation.
  3. Dining Philosophers Problem
    • Five philosophers sit around a table with five chopsticks.
    • Each philosopher needs two chopsticks to eat.
    • Demonstrates resource allocation problems.
    • Improper allocation can cause deadlock and starvation.
  4. Sleeping Barber Problem
    • A barber cuts hair when customers are present and sleeps when the shop is empty.
    • The shop has a limited number of waiting chairs.
    • If all chairs are occupied, a new customer leaves.
    • Requires synchronization between the barber and customers to avoid race conditions.

Quick Revision

Producer-Consumer → Buffer Readers-Writers → Shared resource Dining Philosophers → Chopsticks / Deadlock Sleeping Barber → Waiting chairs / Synchronization

Busy Waiting

“Busy waiting is a situation where a process continuously checks whether a condition or resource is available instead of going to sleep or blocking. It keeps using the CPU while waiting.”

Example

A process wants to enter a critical section but the lock is already held:

Check lock → Still busy → Check again → Still busy → Check again...

The process keeps checking instead of being blocked.

Why is it a Problem?

  • Wastes CPU cycles.
  • Reduces CPU efficiency.
  • Can increase power consumption.
  • Especially inefficient when the waiting time is long.

Busy Waiting vs Blocking

Busy Waiting → Process continuously checks and uses CPU. Blocking → Process sleeps and CPU is given to another process.

Thrashing

Interview-ready answer:

“Thrashing is a condition in a virtual memory system where the system spends most of its time swapping pages between main memory and disk instead of executing processes.”

Why Does Thrashing Occur?

  • Too many processes in memory.
  • Insufficient physical memory.
  • High page fault rate.
  • Processes do not have enough frames to hold their working sets.

What Happens?

More Page Faults → More Disk I/O → Less CPU Utilization → More Waiting → More Page Faults

The system becomes extremely slow.

Example

“If too many processes are running and each process needs more pages than the available RAM can hold, pages are continuously swapped in and out. The CPU spends more time handling page faults than executing processes.”

Effects

  • Very high page-fault rate.
  • Heavy disk I/O.
  • Low CPU utilization.
  • Significant performance degradation.

How to Reduce Thrashing?

  • Reduce the degree of multiprogramming.
  • Allocate more memory/frames.
  • Use working-set model.
  • Use page-fault frequency (PFF) control.

Solutions to the Critical Section Problem

Critical section solutions can be classified into four main categories:

1. Software-Based Solutions

  • Lock Variable
  • Strict Alternation (Turn Variable)
  • Peterson’s Solution
  • Dekker’s Algorithm
  • Lamport’s Bakery Algorithm

2. Hardware-Based Solutions

  • Test-and-Set Lock (TSL)
  • Compare-and-Swap (CAS)
  • Disable Interrupts

3. Operating System-Based Solutions

  • Binary Semaphore
  • Counting Semaphore

4. Compiler-Based Solutions

  • Monitors

Lock Variable

“A lock variable is a simple software-based technique used to control access to a critical section. A shared variable, usually called lock, indicates whether the critical section is free or occupied.”

How It Works

  • lock = 0 → Critical section is free.
  • lock = 1 → Critical section is occupied.
  • A process checks the lock before entering.
  • After completing the critical section, it releases the lock.

Basic Idea

Pseudocode
while (lock == 1);
lock = 1;
// Critical Section
lock = 0;

Problem with Lock Variable

Lock variable alone is not a correct solution to the critical-section problem.

The problem is that checking the lock and setting the lock are separate operations.

Example:

  • Process P1 checks lock == 0.
  • Before P1 sets lock = 1, the CPU switches to P2.
  • P2 also checks lock == 0.
  • P2 sets lock = 1 and enters the critical section.
  • P1 resumes, sets lock = 1, and also enters.

Now both processes can enter the critical section, violating mutual exclusion.

Lock Variable — Important Points

  • It uses a shared lock variable.
  • It is a busy-waiting solution because a process continuously checks the lock.
  • It can be used for more than two processes.
  • However, it does not guarantee mutual exclusion because checking and setting the lock are not atomic.
  • Therefore, lock variable is not a valid solution to the critical-section problem.
RequirementLock VariableExplanation
Mutual Exclusion❌ NoCheck and set operations are not atomic, so two processes can enter the critical section simultaneously.
Progress❌ NoDue to race conditions, a process may be delayed even when the critical section is free.
Bounded Waiting❌ NoA process may wait indefinitely, leading to starvation.
No Hardware/Software Assumption✅ YesIt does not depend on specific hardware or processor speed.

Strict Alternation (Turn Variable)

“Strict Alternation is a software-based solution for the critical-section problem that uses a shared turn variable to decide which process gets the chance to enter the critical section.”

It is designed for two processes.

How It Works

  • turn = 0 → Process P0 can enter.
  • turn = 1 → Process P1 can enter.
  • After leaving the critical section, a process gives the turn to the other process.
  • It uses busy waiting.
Pseudocode
while (turn != i);
// Critical Section
turn = j;

Example

P0 → Critical Section → P1 → Critical Section → P0 → ...

The processes must strictly take turns.

Does It Meet Critical Section Requirements?

RequirementStrict AlternationExplanation
Mutual Exclusion✅ YesOnly the process whose turn it is can enter.
Progress❌ NoA process may be forced to wait even when the other process is not interested in entering.
Bounded Waiting✅ YesA process waits for at most one turn of the other process.
No Hardware/Software Assumption✅ YesIt is a software-based solution and does not depend on hardware speed.

Main Problem

Progress violation.

Suppose P0 enters and then sets turn = 1. If P1 is doing its remainder section and does not want to enter the critical section, P0 still has to wait for P1's turn.

“Strict alternation guarantees mutual exclusion but violates progress because one process can block the other even when it does not want to enter the critical section.”

Peterson’s Solution

“Peterson’s Solution is a software-based synchronization algorithm that provides a correct solution to the critical-section problem for two processes. It uses two shared variables: flag[] and turn.”

Shared Variables

  • flag[i] → Indicates whether process Pi wants to enter the critical section.
  • turn → Indicates which process should get priority if both want to enter.

Basic Idea

Each process:

  1. Sets its flag to true to show that it wants to enter.
  2. Gives the other process the turn.
  3. Waits if the other process also wants to enter and it is the other's turn.
  4. Enters the critical section.
  5. Sets its flag to false after leaving.
Pseudocode
flag[i] = true;
turn = j;
while (flag[j] && turn == j);
// Critical Section
flag[i] = false;
// Remainder Section

Does It Meet Critical Section Requirements?

RequirementPeterson's SolutionExplanation
Mutual Exclusion✅ YesBoth processes cannot enter the critical section simultaneously.
Progress✅ YesIf the critical section is free, a process that wants to enter can proceed.
Bounded Waiting✅ YesA process cannot be postponed indefinitely.
No Hardware/Software Assumption✅ YesIt is a software-based solution and does not depend on special hardware instructions.

Important Points

  • Works for exactly two processes.
  • Uses busy waiting.
  • Provides mutual exclusion, progress, and bounded waiting.
  • Does not require special hardware instructions.
  • Mainly important for theoretical understanding; modern systems generally use hardware-supported synchronization primitives.

Dekker’s Algorithm

“Dekker’s Algorithm is a software-based solution for the critical-section problem for two processes. It uses flags and a turn variable to achieve mutual exclusion, progress, and bounded waiting.”

  • Supports 2 processes.
  • Uses busy waiting.
  • Provides mutual exclusion, progress, and bounded waiting.
  • Does not require special hardware instructions.

Interview one-liner:

“Dekker’s Algorithm uses flags and turn to safely coordinate two processes without hardware support.”

Lamport’s Bakery Algorithm

“Lamport’s Bakery Algorithm is a software-based solution that provides mutual exclusion for multiple processes using a ticket-number system, similar to customers taking tokens at a bakery.”

  • Supports multiple processes.
  • Each process takes a unique/ordered ticket number.
  • Process with the smallest ticket enters first.
  • Provides mutual exclusion, progress, and bounded waiting.
  • Uses busy waiting.

Interview one-liner:

“Lamport’s Bakery Algorithm uses ticket numbers to decide which process enters the critical section next, and it can handle multiple processes.”

Test-and-Set Lock (TSL)

“Test-and-Set is a hardware-based atomic instruction used to implement locks for mutual exclusion. It checks the current value of a lock and sets it simultaneously as one indivisible operation.”

Test-and-Set Function

Pseudocode
bool TestAndSet(bool *lock) {
    bool old = *lock;
    *lock = true;
    return old;
}

The function:

  • Returns the old value of lock.
  • Sets lock = true.
  • Both operations happen atomically.

How It Works

Pseudocode
while (TestAndSet(&lock));
// Critical Section
lock = false;
  • If lock = false → TestAndSet() returns false → process enters.
  • If lock = true → TestAndSet() returns true → process keeps waiting.
  • After leaving the critical section → lock = false.

Does It Meet Critical Section Requirements?

RequirementTSLExplanation
Mutual Exclusion✅ YesAtomic test-and-set ensures only one process acquires the lock.
Progress✅ YesIf the lock is free, a waiting process can acquire it.
Bounded Waiting❌ NoA process may repeatedly lose the lock and wait indefinitely.
No Hardware/Software Assumption❌ NoIt requires a hardware-supported atomic instruction.

Important Point

TSL uses busy waiting.

The process continuously checks the lock while waiting, so CPU cycles can be wasted. This is why it is commonly associated with a spinlock.

Compare-and-Swap (CAS)

“Compare-and-Swap is a hardware-supported atomic instruction used to implement synchronization mechanisms such as locks. It compares a memory location with an expected value and updates it only if they are equal.”

CAS Function

Pseudocode
bool CompareAndSwap(int *value, int expected, int newValue) {
    if (*value == expected) {
        *value = newValue;
        return true;
    }
    return false;
}

The operation is atomic, meaning no other process can interrupt it between the comparison and update.

How It Works

Suppose:

lock = 0 → unlocked lock = 1 → locked

Pseudocode
while (!CompareAndSwap(&lock, 0, 1));
// Critical Section
lock = 0;
  • If lock == 0 → CAS changes it to 1 → process enters.
  • If lock == 1 → CAS fails → process keeps waiting.
  • After leaving → lock = 0.

Does It Meet Critical Section Requirements?

RequirementCASExplanation
Mutual Exclusion✅ YesAtomic comparison and update ensures only one process acquires the lock.
Progress✅ YesIf the lock is free, a process can acquire it.
Bounded Waiting❌ Not guaranteedBasic CAS-based locking can cause starvation.
No Hardware/Software Assumption❌ NoRequires hardware support for atomic CAS.

Important Point

CAS can be used to implement spinlocks, so a process may perform busy waiting while the lock is unavailable.

TSL vs CAS

TSL → Test old value and set lock. CAS → Compare with expected value and change to a new value only if they match.

Disable Interrupts

“Disabling interrupts is a hardware-based technique used to protect a critical section by preventing the CPU from being interrupted while the critical section is executing.”

How It Works

  1. Process enters the critical section.
  2. CPU disables interrupts.
  3. Process executes the critical section without being preempted by interrupts.
  4. Process exits the critical section.
  5. CPU enables interrupts again.
Pseudocode
DisableInterrupts();
// Critical Section
EnableInterrupts();

Does It Meet Critical Section Requirements?

RequirementDisable InterruptsExplanation
Mutual Exclusion⚠️ LimitedOn a single CPU, preventing interrupts can prevent preemption, but it is not a general solution for multiple CPUs.
Progress⚠️ LimitedCan provide progress on a single CPU, but has practical limitations.
Bounded Waiting❌ NoIt does not guarantee bounded waiting or prevent starvation.
No Hardware/Software Assumption❌ NoDirectly depends on hardware/privileged CPU support.

Important Limitations

  • Mainly applicable to single-processor systems.
  • On multiprocessor systems, disabling interrupts on one CPU does not stop another CPU from accessing the shared resource.
  • Only the kernel should normally be allowed to disable interrupts.
  • Keeping interrupts disabled for too long can affect system responsiveness.

Interview One-Liner

“Disabling interrupts can protect a critical section on a single CPU by preventing interrupt-driven preemption, but it is not suitable as a general synchronization mechanism for multiprocessor systems.”

Semaphore

“A semaphore is a synchronization mechanism used by the operating system to control access to shared resources and coordinate processes or threads.”

A semaphore is an integer variable that can only be accessed through atomic operations.

Main Operations

1. Wait / P / Down

  • Decreases the semaphore value.
  • If the resource is unavailable, the process blocks/waits.

2. Signal / V / Up

  • Increases the semaphore value.
  • Wakes up a waiting process if one exists.
Pseudocode
wait(S);
// Critical Section
signal(S);

Mutex

“A mutex (Mutual Exclusion) is a locking mechanism that allows only one thread or process at a time to access a shared resource or critical section.”

Key Points

  • Lock: Acquire mutex before entering the critical section.
  • Unlock: Release mutex after leaving.
  • Blocking: If mutex is already locked, other threads wait.
  • Ownership: Usually, the thread that locks the mutex must unlock it.
  • Prevents race conditions and protects shared data.

Mutex vs Semaphore

a mutex is a locking mechanism meant for one task at a time, while a semaphore is a signaling mechanism that manages multiple tasks at once.

FeatureMutexSemaphore
TypeObject/locking mechanismInteger-based synchronization mechanism
PurposeMutual exclusionResource management and signaling
OperationsLock / UnlockWait / Signal
AccessOnly one thread at a timeMultiple threads depending on count
OwnershipHas ownership; usually the owner unlocks itNo ownership
ValueLocked / UnlockedInteger count
TypesNo standard subtypesBinary & Counting Semaphore
ExampleProtect one shared variableManage 3 identical resources

Types of Semaphore

There are mainly two types of semaphores:

1. Binary Semaphore

  • Value can be 0 or 1.
  • Used mainly for mutual exclusion.
  • Only one process/thread can access the protected resource at a time.
  • Similar to a lock.

Example: Protecting a critical section.

2. Counting Semaphore

  • Value can be any non-negative integer.
  • Used to manage multiple instances of a resource.
  • Allows multiple processes/threads to access the resource up to the semaphore count.

Example: If there are 3 printers, initialize semaphore to 3.

Value Interpretation

“A counting semaphore is an integer-valued semaphore used to manage multiple instances of a shared resource.”

In the classic Dijkstra semaphore model, the semaphore value can be positive, zero, or negative.

  • S > 0: Number of resources currently available.
  • S = 0: No resources are available and no process is waiting.
  • S < 0: |S| represents the number of processes waiting/blocked.

Example:

If S = -3, it means 3 processes are waiting in the semaphore queue.

Wait and Signal Operations

“wait() and signal() are the two fundamental atomic operations used to operate on a semaphore.”

1. Wait() — P / Down

  • Used to acquire a resource.
  • Decreases the semaphore value.
  • If the resource is unavailable, the process blocks/waits.

Conceptually:

Pseudocode
wait(S) {
    S--;
    if (S < 0)
        block();
}

2. Signal() — V / Up

  • Used to release a resource.
  • Increases the semaphore value.
  • If processes are waiting, one of them can be woken up.

Conceptually:

Pseudocode
signal(S) {
    S++;
    if (S <= 0)
        wakeup();
}

Example

For a semaphore S = 3:

wait(S) → S = 2 → resource acquired wait(S) → S = 1 → resource acquired signal(S) → S = 2 → resource released

Important Point

Wait and Signal must be atomic operations. Otherwise, race conditions can occur while modifying the semaphore.

Monitors

“A monitor is a high-level synchronization construct that allows only one process or thread to execute inside it at a time. It provides mutual exclusion for shared data and operations.”

Key Points

  • High-level synchronization mechanism.
  • Automatically provides mutual exclusion.
  • Only one process/thread can execute inside the monitor at a time.
  • Shared data is kept inside the monitor.
  • Uses condition variables such as wait() and signal() for coordination.
  • Helps prevent race conditions.

Example

A monitor protecting a shared buffer may provide:

  • insert() → Producer adds data.
  • remove() → Consumer removes data.
  • wait() → Process waits when the buffer is full/empty.
  • signal() → Wakes a waiting process when the condition changes.

Monitor vs Semaphore

Monitor → High-level, automatic mutual exclusion.

Semaphore → Lower-level, programmer explicitly uses wait() and signal().

Priority Inversion

Priority inversion is a scheduling problem where a high-priority process is indirectly blocked by a low-priority process because the low-priority process holds a shared resource or lock required by the high-priority process.

How Priority Inversion Happens

Suppose there are three processes:

  • L → Low Priority
  • M → Medium Priority
  • H → High Priority
  1. L acquires a lock on a shared resource.
  2. H starts and needs the same resource, so H blocks and waits for L.
  3. M becomes ready and preempts L because M has higher priority than L.
  4. M continues running while L cannot release the lock.
  5. Therefore, H is indirectly delayed by M, even though H has the highest priority.

Flow:

L holds lock → H waits for L → M preempts L → H remains blocked

Why Is It a Problem?

  • High-priority processes can experience unexpected delays.
  • Can cause missed deadlines in real-time systems.
  • In severe cases, the high-priority process may be delayed indefinitely.

Solutions

Solutions to Priority Inversion

  • Priority Inheritance Protocol: The system temporarily boosts the priority of the low-priority task (L) to match the high-priority task (H) as long as L holds the needed lock. This stops medium-priority tasks (M) from interrupting L, allowing L to release the resource quickly.
  • Priority Ceiling Protocol: Every shared resource is assigned a priority ceiling equal to the highest priority task that can ever use it. Any task that locks the resource immediately gets raised to that ceiling priority level, preventing inversion altogether.

Livelock in Priority Inversion

Livelock occurs when processes are continuously changing their state or responding to each other but no process makes meaningful progress.

In the context of priority inversion, livelock can occur when scheduling or synchronization mechanisms repeatedly change priorities or cause processes to retry, preventing useful work from progressing.

Example

Suppose:

  • L → Low priority
  • M → Medium priority
  • H → High priority

If the synchronization mechanism repeatedly causes processes to change priorities, release/ reacquire locks, or retry, the processes may remain active but fail to complete their required work.

Livelock vs Deadlock

Deadlock → Processes are blocked and do nothing.

Livelock → Processes are active but make no progress.

Producer-Consumer Solution Using Semaphores

“The Producer-Consumer problem can be solved using semaphores to synchronize access to a shared bounded buffer and prevent race conditions.”

Semaphores Used

For a buffer of size N, we use three semaphores:

  • empty = N → Number of empty slots in the buffer.
  • full = 0 → Number of filled slots in the buffer.
  • mutex = 1 → Provides mutual exclusion while accessing the buffer.

Producer

Pseudocode
wait(empty);
wait(mutex);
// Add item to buffer
signal(mutex);
signal(full);
  • wait(empty) → Ensures the buffer is not full.
  • wait(mutex) → Enters the critical section.
  • Adds an item.
  • signal(mutex) → Leaves the critical section.
  • signal(full) → Increases the number of available items.

Consumer

Pseudocode
wait(full);
wait(mutex);
// Remove item from buffer
signal(mutex);
signal(empty);
  • wait(full) → Ensures the buffer is not empty.
  • wait(mutex) → Enters the critical section.
  • Removes an item.
  • signal(mutex) → Leaves the critical section.
  • signal(empty) → Increases the number of empty slots.

Important Interview Point

Why do we need three semaphores?

empty → Prevents Producer from adding to a full buffer. full → Prevents Consumer from removing from an empty buffer. mutex → Prevents Producer and Consumer from accessing the buffer simultaneously.

Readers-Writers Problem

“The Readers-Writers problem deals with synchronizing multiple processes that access a shared resource. Multiple readers can access the resource simultaneously, but a writer requires exclusive access.”

Rules

  • Multiple readers can read simultaneously.
  • Only one writer can write at a time.
  • When a writer is writing, no reader or other writer can access the resource.
  • Synchronization is required to prevent race conditions.
  • Poor scheduling can cause starvation.

Semaphores Used

Commonly, two semaphores are used:

  • mutex = 1 → Protects the readCount variable.
  • rw_mutex = 1 → Controls access to the shared resource.

readCount → Number of readers currently reading.

Reader

Pseudocode
wait(mutex);
readCount++;
if (readCount == 1)
    wait(rw_mutex);
signal(mutex);
// Reading
wait(mutex);
readCount--;
if (readCount == 0)
    signal(rw_mutex);
signal(mutex);

Writer

Pseudocode
wait(rw_mutex);
// Writing
signal(rw_mutex);

How It Works

  • The first reader locks rw_mutex, preventing writers.
  • Other readers can enter simultaneously.
  • The last reader releases rw_mutex.
  • A writer must acquire rw_mutex, so it gets exclusive access.

Important Interview Point

Readers can share the resource with other readers, but writers cannot share it with anyone.

Problem

The reader-preference solution can cause writer starvation if readers continuously arrive.

Dining Philosophers Solution Using Semaphores

“The Dining Philosophers problem demonstrates synchronization when multiple processes compete for limited shared resources. Semaphores can be used to control access to the chopsticks and prevent deadlock.”

Basic Idea

There are 5 philosophers and 5 chopsticks.

Each philosopher needs two chopsticks to eat:

  • Left chopstick
  • Right chopstick

We use:

  • chopstick[5] → Binary semaphore for each chopstick, initialized to 1.
  • mutex = 1 → Controls access to the process of picking up chopsticks.

Semaphore Setup

Pseudocode
semaphore chopstick[5] = {1, 1, 1, 1, 1};
semaphore mutex = 1;

Philosopher

Pseudocode
wait(mutex);
wait(chopstick[i]);
wait(chopstick[(i + 1) % 5]);
signal(mutex);
// Eat
signal(chopstick[(i + 1) % 5]);
signal(chopstick[i]);

How It Works

  1. Philosopher requests permission using wait(mutex).
  2. Picks up the left chopstick.
  3. Picks up the right chopstick.
  4. Eats.
  5. Releases both chopsticks.
  6. Other philosophers can then use them.

Why Does mutex Help?

Without mutex, all five philosophers could pick up their left chopstick simultaneously.

Then everyone waits for their right chopstick:

P0 holds left → waits for right P1 holds left → waits for right P2 holds left → waits for right P3 holds left → waits for right P4 holds left → waits for right

This creates deadlock.

By allowing only one philosopher at a time to acquire chopsticks, this particular solution prevents that circular waiting situation.

Important Point

This solution prevents deadlock, but synchronization designs should also consider starvation/ fairness.

6. Multi-Threading Models

Thread

“A thread is the smallest unit of CPU execution within a process. A process can contain multiple threads that share the same process resources but execute independently.”

Key Points

  • A thread is a lightweight unit of execution.
  • Threads belonging to the same process share:
    • Code
    • Data
    • Heap
    • Open files/resources
  • Each thread has its own:
    • Program Counter (PC)
    • Registers
    • Stack
  • Multiple threads can execute concurrently.
  • Threads are generally faster and cheaper to create and switch than processes.
Key Points

Why Do We Need Threads?

Threads are needed to perform multiple tasks concurrently within the same process.

Main Reasons

  • Concurrency: Multiple tasks can progress at the same time.
  • Better CPU Utilization: While one thread waits for I/O, another can use the CPU.
  • Responsiveness: Applications remain responsive while background tasks run.
  • Resource Sharing: Threads of the same process share memory and resources.
  • Faster Communication: Threads can communicate through shared memory more easily than separate processes.
  • Lower Overhead: Creating and switching threads is generally cheaper than creating and switching processes.
  • Parallelism: On multi-core CPUs, multiple threads can execute in parallel.

Types of Threads

There are mainly two types of threads:

1. User-Level Threads

“User-level threads are managed by a user-level thread library rather than directly by the operating system kernel.”

  • Managed by user-level libraries.
  • Kernel may not know about individual threads.
  • Fast to create and switch.
  • If one thread performs a blocking system call, the entire process may block.
  • Cannot achieve true parallelism on multiple cores in many-to-one models.

Examples: POSIX Pthreads, Java threads depending on implementation.

2. Kernel-Level Threads

“Kernel-level threads are directly managed by the operating system kernel.”

  • Managed by the OS kernel.
  • Kernel schedules individual threads.
  • If one thread blocks, other threads can continue.
  • Can achieve true parallelism on multi-core CPUs.
  • Creation and context switching generally have higher overhead than user-level threads.

Process vs Thread — 5 Differences

FeatureProcessThread
1. DefinitionIndependent program in execution.Smallest unit of execution within a process.
2. MemoryHas its own separate address space.Shares memory/address space with other threads of the same process.
3. Resource SharingResources are generally independent.Shares code, data, heap, and open files with other threads.
4. Creation & SwitchingMore expensive and slower.Less expensive and faster.
5. FailureFailure of one process generally does not directly affect another process.Failure of one thread can affect the entire process.

Deadlock

A Deadlock is a situation where each of the computer process waits for a resource which is being assigned to some another process. In this situation, none of the process gets executed since the resource it needs, is held by some other process which is also waiting for some other resource to be released.

7. Deadlocks & Resource Allocation

Deadlock vs Starvation vs Livelock

FeatureDeadlockStarvationLivelock
MeaningProcesses wait for each other indefinitely.A process waits indefinitely because other processes keep getting resources/CPU.Processes remain active but make no useful progress.
Process StateUsually blocked/ waiting.Usually ready/waiting for a resource or CPU.Running/active, continuously responding or changing state.
ProgressNo progress.Other processes may make progress, but one process does not.No meaningful progress despite activity.
Main CauseCircular resource dependency.Unfair scheduling/resource allocation.Processes repeatedly react to each other.
ExampleP1 waits for P2's resource, while P2 waits for P1's resource.Low-priority process keeps waiting while higher-priority processes are repeatedly scheduled.Two processes repeatedly change/retry their actions to avoid conflict but neither completes.
SolutionPrevention, avoidance, detection & recovery.Aging, fair scheduling, bounded waiting.Better synchronization, backoff, or randomized waiting.

Easy Way to Remember

Deadlock → Stuck and waiting

Starvation → One process keeps waiting

Livelock → Active but not progressing

Necessary Conditions for Deadlock

Deadlock can occur only when all four conditions exist simultaneously:

1. Mutual Exclusion

  • A resource can be used by only one process at a time.
  • It cannot be shared simultaneously.

2. Hold and Wait

  • A process holds one or more resources while waiting for additional resources.

3. No Preemption

  • A resource cannot be forcibly taken from a process.
  • The process must release the resource voluntarily.

4. Circular Wait

  • A circular chain of processes exists.
  • Each process is waiting for a resource held by the next process.

Strategies for Handling Deadlock

There are four main strategies for handling deadlocks:

1. Deadlock Prevention

Ensure that at least one of the four necessary conditions for deadlock never occurs.

  • Break Mutual Exclusion
  • Break Hold and Wait
  • Allow Preemption
  • Prevent Circular Wait

2. Deadlock Avoidance

The OS checks resource allocation before granting a request and ensures the system remains in a safe state.

  • Banker's Algorithm is the most common example.
  • Requires information about future resource requirements.

3. Deadlock Detection and Recovery

Allow deadlocks to occur, then detect them and recover from them.

Recovery methods:

  • Terminate processes.
  • Preempt resources.
  • Roll back processes.

4. Ignore the Deadlock

The OS simply ignores certain deadlocks if detecting and preventing them is too expensive or the deadlock is rare.

This approach is sometimes called the Ostrich Algorithm.

Easy Revision

Prevention → Make deadlock impossible

Avoidance → Stay in a safe state

Detection & Recovery → Detect and fix

Ignore → Do nothing

Deadlock Prevention

“Deadlock prevention is a technique that ensures at least one of the four necessary conditions for deadlock never occurs.”

Methods of Deadlock Prevention

1. Prevent Mutual Exclusion

  • Allow multiple processes to use a resource simultaneously (where possible) .
  • Example: Read-only files can be shared.
  • Not possible for inherently non-shareable resources like printers.

2. Prevent Hold and Wait

  • A process must request all required resources at once before execution.
  • Or, it must release currently held resources before requesting new ones.

3. Prevent No Preemption

  • Allow preemption of resources. If a process requests a resource that’s unavailable, force the process holding the requested resource to release it

4. Prevent Circular Wait

  • Assign a unique priority number to each resource, and processes must request resources in a strict priority order, preventing circular chains of waiting. o This is the most practical method to implement.

Easy Revision

Mutual Exclusion → Make resources shareable

Hold & Wait → Request all resources together

No Preemption → Take/release resources when necessary

Circular Wait → Follow resource ordering

Deadlock Detection

“Deadlock detection allows deadlocks to occur and then checks whether the system has entered a deadlocked state.”

The detection method depends on whether resources have single or multiple instances.

1. Single Instance of Each Resource

Use a Resource Allocation Graph (RAG).

A Resource Allocation Graph contains:

  • Process nodes: represented by circles.
  • Resource nodes: represented by rectangles.
  • Request edge: P → R means the process is requesting the resource.
  • Allocation edge: R → P means the resource is allocated to the process.

If every resource has only one instance:

Cycle in RAG → Deadlock

Example:

P1 → R2 → P2 → R1 → P1

This cycle indicates deadlock.

A Wait-For Graph (WFG) can also be used by removing resource nodes:

P1 → P2 means P1 is waiting for a resource held by P2.

Cycle in WFG → Deadlock

2. Multiple Instances of Resources

A Resource Allocation Graph alone is not sufficient to determine deadlock simply by looking for a cycle, because a resource type may have multiple instances.

Use a Deadlock Detection Algorithm based on:

  • Available → Currently available resources.
  • Allocation → Resources currently allocated to each process.
  • Request → Resources currently requested by each process.

The algorithm checks whether processes can finish one by one using the available resources.

  • If all processes can finish → No deadlock.
  • If some processes cannot finish → Those processes are deadlocked.

Easy Revision

Single Instance → Resource Allocation Graph → Cycle = Deadlock

Single Instance → Wait-For Graph → Cycle = Deadlock

Multiple Instances → Detection Algorithm → Available + Allocation + Request

Deadlock Recovery

“Deadlock recovery is the process of restoring the system to a safe state after a deadlock has been detected.”

There are mainly two approaches:

1. Process Termination

Terminate one or more processes involved in the deadlock.

  • Terminate all deadlocked processes → Fast but causes more loss of work.
  • Terminate one process at a time → Continue until the deadlock is removed.

The OS may consider:

  • Process priority.
  • Resources held by the process.
  • Resources still required.
  • How much work the process has completed.

2. Resource Preemption

“Take a resource from one process and allocate it to another process to break the deadlock.”

Steps:

  1. Select a victim → Choose a process whose resource will be taken.
  2. Preempt the resource → Take the resource from that process.
  3. Rollback → Restore the affected process to a previous safe state.
  4. Restart → Continue the process later.

Problems with Recovery

  • Starvation: The same process may repeatedly be selected as the victim.
  • Data loss: Terminating or rolling back processes can cause loss of work.
  • Overhead: Recovery operations consume system resources.

Easy Revision

Deadlock Detected → Recover

Process Termination → Kill processes

Resource Preemption → Take resource + Rollback

Deadlock Avoidance

“Deadlock avoidance is a technique where the OS carefully allocates resources and ensures that the system always remains in a safe state, thereby avoiding deadlock.”

Basic Idea

Before allocating a resource, the OS checks:

“Will granting this request keep the system in a safe state?”

  • If Yes → Resource is allocated.
  • If No → Process must wait.

Safe State

A system is in a safe state if there exists at least one safe sequence in which all processes can complete their execution without causing deadlock.

Safe State ≠ Deadlock

Unsafe State ≠ Guaranteed Deadlock, but it means the system may enter deadlock.

Algorithms Used

1. Banker's Algorithm

  • Used when resources have multiple instances.
  • Checks whether allocating resources keeps the system safe.

2. Resource Allocation Graph Algorithm

  • Used for systems with single instances of each resource type.
  • Uses claim/request information to determine whether allocation can safely proceed.

Requirements

Deadlock avoidance generally requires the OS to know information such as:

  • Available resources
  • Currently allocated resources
  • Maximum resource requirements of processes

Prevention vs Avoidance

Deadlock Prevention → Break one of the four necessary conditions.

Deadlock Avoidance → Carefully allocate resources to remain in a safe state.

Banker's Algorithm

“Banker’s Algorithm is a deadlock-avoidance algorithm that checks whether granting a resource request will keep the system in a safe state.”

It is mainly used when multiple instances of resources are available.

Main Data Structures

  1. Available
    • Number of currently available instances of each resource.
  2. Max
    • Maximum resources each process may need.
  3. Allocation
    • Resources currently allocated to each process.
  4. Need
    • Remaining resources required by each process.

Formula:

Need = Max − Allocation

Basic Steps

  1. Calculate the Need matrix.
  2. Find a process whose: Need ≤ Available
  3. Assume that process completes.
  4. Add its allocated resources back: Available = Available + Allocation
  5. Repeat for all processes.
  6. If all processes can finish → Safe State.
  7. If no suitable process can be found → Unsafe State.

Example Idea

Suppose:

Available = 3

Process P1 needs 2 resources.

Since:

Need(P1) ≤ Available

P1 can finish.

After P1 finishes, its allocated resources are released and added to Available. Then another process may become able to finish.

This creates a Safe Sequence.

Safe Sequence

A sequence such as:

P1 → P3 → P4 → P0 → P2

means processes can complete in this order without causing deadlock.

Important Point

Safe State → At least one safe sequence exists.

Unsafe State → No safe sequence can be found; deadlock is possible.

8. Main Memory Management & Allocation Strategies

Memory Management

Memory Management is an important function of the operating system that manages main memory (RAM) and controls how memory is allocated and used by processes.

The OS is responsible for:

  • Allocating memory to processes.
  • Deallocating memory when a process finishes.
  • Keeping track of which memory areas are free and occupied.
  • Protecting one process's memory from another.
  • Supporting virtual memory when RAM is insufficient.
  • Efficiently using available memory.

Goal: - Efficient utilization of memory by minimizing the internal and external fragmentation.

Introduction to Memory

Memory is a storage area used by the computer to store data and instructions that are currently being used by the CPU.

The CPU directly works with data and instructions present in main memory (RAM).

A simple flow is:

Secondary Storage → RAM → CPU

Memory Units

Memory is measured using different units:

  • 1 Bit = Smallest unit of memory, either 0 or 1.
  • 1 Byte (B) = 8 bits.
  • 1 KB = 1024 Bytes.
  • 1 MB = 1024 KB.
  • 1 GB = 1024 MB.
  • 1 TB = 1024 GB.
  • 1 PB = 1024 TB.

Memory Cell: Smallest storage unit that holds 1 bit of data. Each address in memory typically refers to a byte.

Word & Byte: A word is a group of bits; 1 byte = 8 bits.

Capacity: Total number of bits a memory can hold.

Formula to Find Memory Capacity

The basic formula is:

Memory Capacity = Number of Memory Locations × Bits per Location

Classification of Memory

Classification of Memory

Computer memory is broadly classified into Primary Memory and Secondary Memory.

1. Primary Memory

Primary memory is memory that the CPU can directly access.

  • Faster than secondary memory.
  • Limited capacity.
  • Used to store programs and data currently being processed.
  • Includes RAM and ROM.

RAM — Random Access Memory

RAM is the main working memory of a computer that temporarily stores programs and data currently being used by the CPU.

  • Volatile → Data is lost when power is turned off.
  • Fast access.
  • Supports multitasking.

Types of RAM

SRAM — Static RAM

  • Faster and more expensive.
  • Does not require periodic refreshing.
  • Commonly used for CPU cache.

DRAM — Dynamic RAM

  • Slower and cheaper than SRAM.
  • Requires periodic refreshing.
  • Commonly used as main memory (RAM).
  • Includes SDRAM and DDR variants.

ROM — Read-Only Memory

ROM is non-volatile memory that stores instructions required for system startup and firmware.

  • Data is retained even when power is off.
  • Commonly stores firmware and boot instructions.

Types of ROM

  • MROM: Programmed during manufacturing.
  • PROM: Can be programmed once.
  • EPROM: Can be erased using ultraviolet (UV) light and reprogrammed.
  • EEPROM: Can be electrically erased and reprogrammed.
  • Flash Memory: Electrically erasable/reprogrammable memory widely used in storage devices.

2. Secondary Memory

Secondary memory is used for long-term storage of data and programs.

  • Non-volatile.
  • Larger capacity.
  • Slower than primary memory.
  • CPU does not normally access it directly; data is loaded into RAM before execution.

Examples:

  • HDD
  • SSD
  • USB drives
  • Memory cards
  • Optical discs
  • Magnetic tapes

Easy Revision

Primary Memory → CPU-accessible → Faster → RAM + ROM

Secondary Memory → Long-term storage → Slower + Larger → HDD + SSD + USB etc.

Loading

Loading is the process of transferring an executable program from secondary storage into main memory (RAM) so that the CPU can execute it.

The loader performs this task.

Types of Loading

1. Static Loading

  • Entire program is loaded into memory before execution.
  • Program remains in memory during execution.
  • Memory requirement is determined beforehand.
  • No code/data is loaded on demand.

2. Dynamic Loading

  • Only the required part of the program is loaded initially.
  • Other parts are loaded on demand during execution.
  • Saves memory because unused parts need not be loaded.

Static Loading → Load everything initially

Dynamic Loading → Load when needed

Linking

Linking is the process of combining object files and required libraries to create an executable file.

Static Linking

  • Libraries are included in the executable before execution.
  • Executable size is larger.
  • No need to load those libraries separately at runtime.

Dynamic Linking

  • Libraries are linked/loaded at runtime.
  • Executable contains references to shared libraries.
  • Examples: .so in Linux and .dll in Windows.
  • Reduces executable size and allows libraries to be shared.

Static Linking → Library included in executable

Dynamic Linking → Library loaded when required

Address Binding

Address binding is the process of mapping a program's logical addresses to actual physical memory addresses.

There are three types:

1. Compile-Time Binding

  • Starting memory location is known at compile time.
  • Compiler generates absolute addresses.
  • If the starting address changes, the program must be recompiled.

Known at compile time → Absolute address

2. Load-Time Binding

  • Memory location is not known at compile time.
  • Compiler generates relocatable code.
  • Loader adjusts addresses when loading the program into memory.

Binding happens when program is loaded

3. Execution-Time / Dynamic Binding

  • Address mapping is performed during execution.
  • Process can be moved from one memory location to another.
  • Requires hardware support such as the MMU (Memory Management Unit).

Binding happens during execution → MMU required

3. Execution-Time / Dynamic Binding

Techniques in Memory Allocation

Memory allocation is the process of assigning available memory space to processes when they need it.

There are two major techniques:

1. Contiguous Memory Allocation

A process is allocated one continuous block of physical memory.

Types:

  • Fixed Partitioning
  • Variable/Dynamic Partitioning

Advantages:

  • Simple to implement.
  • Fast memory access.

Disadvantages:

  • Can cause internal or external fragmentation.
  • Difficult to utilize memory efficiently.

2. Non-Contiguous Memory Allocation

A process can be divided into multiple parts and stored in different locations in memory.

Types:

  • Paging
  • Segmentation
  • Segmentation with Paging

Advantages:

  • Better memory utilization.
  • Reduces external fragmentation.
  • Supports virtual memory.

Disadvantages:

  • More complex memory management.
  • Requires additional data structures such as page tables or segment tables.
2. Non-Contiguous Memory Allocation

Fixed Partitioning

Fixed Partitioning is a contiguous memory allocation technique in which main memory is divided into a fixed number of partitions of fixed sizes before or during system operation.

Each partition can hold at most one process.

How It Works

Suppose RAM is divided into 4 partitions:

100 MB | 200 MB | 300 MB | 400 MB

If a process requires 150 MB:

  • It can be placed in the 200 MB partition.
  • The remaining 50 MB inside that partition cannot be used by another process.

Types

1. Equal-Sized Partitions

  • All partitions have the same size.
  • Simple to implement.
  • Can waste more memory for small processes.

2. Unequal-Sized Partitions

  • Partitions have different sizes.
  • A process can be placed in a suitably sized partition.
  • Provides better memory utilization than equal-sized partitions.

Advantages

  • Simple and easy to implement.
  • Low management overhead.
  • Fast allocation and deallocation.

Disadvantages of Fixed Partitioning

  1. Internal Fragmentation Unused space inside an allocated partition is wasted. Example: 4 MB partition − 3 MB process = 1 MB wasted.
  2. External Fragmentation Free space exists but is divided into separate non-contiguous blocks, so it cannot be used for a larger process.
  3. Process Size Limitation A process larger than the largest partition cannot be loaded.
  4. Low Degree of Multiprogramming Maximum number of processes is limited by the number of partitions.
Disadvantages of Fixed Partitioning

Variable / Dynamic Partitioning

Variable partitioning is a contiguous memory allocation technique where partitions are created dynamically according to the size of the process.

  • Partition size is not fixed.
  • A process gets memory approximately equal to its requirement.
  • Better memory utilization than fixed partitioning.
  • Causes external fragmentation.
  • Does not usually cause internal fragmentation.

Example:

Process = 10 MB → Allocate 10 MB

Process = 25 MB → Allocate 25 MB

Advantages

  • Better memory utilization.
  • No fixed partition size.
  • Process size is not limited by predefined partitions.

Disadvantages of Variable Partitioning

1. External Fragmentation

  • Free memory becomes divided into small, non-contiguous blocks.
  • A process may not fit even if the total free memory is sufficient.
  • Example: Two free blocks of 1 MB + 1 MB cannot hold a 2 MB process because they are not contiguous.

2. Complex Memory Allocation

  • Partition sizes change dynamically.
  • OS must continuously track allocated and free memory blocks.
  • Allocation and deallocation are more complex.

Compaction

Compaction combines scattered free memory into one large contiguous block by moving processes.

Purpose: Reduce external fragmentation.

Disadvantage:

  • Computationally expensive.
  • Moving large amounts of memory takes significant time.
  • Processes may need to be temporarily paused during relocation.
Compaction

Swapping

Swapping is a memory management technique in which a process is temporarily moved between main memory (RAM) and secondary storage to free RAM for other processes.

How It Works

  • Swap Out: Process is moved from RAM → secondary storage.
  • Swap In: Process is brought back from secondary storage → RAM.
  • The process can continue execution after being swapped back in.

Advantages

  • Allows more processes to be handled with limited RAM.
  • Improves degree of multiprogramming.
  • Higher-priority processes can be brought into memory when needed.

Disadvantage

  • Swapping is slow because secondary storage is much slower than RAM.
  • Transfer time depends on the amount of data being moved.

Partition Allocation Policies

Partition allocation policies decide which free memory block should be allocated to a process in variable/dynamic partitioning.

1. First Fit

  • Start searching from the beginning of memory.
  • Allocate the first block large enough for the process.
  • Fast and simple.

First suitable block → Allocate

2. Best Fit

  • Search all available blocks.
  • Allocate the smallest block that is large enough.
  • Can create many small free holes.

Smallest suitable block → Allocate

3. Worst Fit

  • Search all available blocks.
  • Allocate the largest available block.
  • Leaves a relatively large remaining block.

Largest block → Allocate

4. Next Fit

  • Similar to First Fit.
  • Starts searching from the position of the last allocation, not from the beginning.
  • Wraps around to the beginning if necessary.

Start from last position → First suitable block

Quick Comparison

PolicySelectsSearch Starts
First FitFirst suitable blockBeginning
Best FitSmallest suitable blockBeginning
Worst FitLargest blockBeginning
Next FitFirst suitable blockLast allocation position

Easy Trick

First Fit → First

Best Fit → Smallest

Worst Fit → Largest

Next Fit → Next from last position

Buddy System

Buddy System is a memory allocation technique that divides memory into blocks of power-of-two sizes and efficiently splits and merges them during allocation and deallocation.

How It Works

Allocation:

Find the smallest power-of-2 block that can satisfy the request.

If the block is too large, repeatedly split it into two equal-sized buddies.

Allocate one buddy and keep the other free.

Deallocation:

Free the allocated block.

Check whether its buddy is also free.

If yes → merge (coalesce) them.

Continue merging upward if possible.

Example

Request = 18 KB

128 KB
↓
64 KB + 64 KB
↓
32 KB + 32 KB

Since 16 KB < 18 KB, allocate 32 KB.

18 KB request → 32 KB allocated → 14 KB internal fragmentation

Key Properties

Blocks are usually powers of 2: 2, 4, 8, 16, 32...

Fast allocation and deallocation

Fast splitting and merging

Reduces external fragmentation

Can cause internal fragmentation

Advantages

Fast allocation/deallocation

Easy coalescing of free blocks

Simple memory management

Reduces external fragmentation

Disadvantages

Internal fragmentation due to power-of-two allocation

Requested size may be much smaller than allocated block

Some memory is wasted

Logical and Physical Address

Logical Address

Logical address is the address generated by the CPU for a process during execution.

  • Also called a virtual address.
  • The process uses logical addresses.
  • It does not directly represent the actual location in RAM.
  • The MMU (Memory Management Unit) translates it into a physical address.

Physical Address

Physical address is the actual address in main memory (RAM) where the data or instruction is stored.

  • Generated after address translation.
  • Used by the memory hardware to access RAM.
  • Different processes can have the same logical address but different physical addresses.

Address Translation

CPU → Logical Address → MMU → Physical Address → RAM

Example:

CPU generates logical address 1000

MMU translates it to physical address 5000

RAM accesses location 5000

Memory Management Unit (MMU)

MMU is a hardware component that translates logical (virtual) addresses generated by the CPU into physical addresses in main memory (RAM).

How MMU Works

CPU → Logical Address → MMU → Physical Address → RAM

Example:

CPU generates Logical Address = 1000

MMU translates it to Physical Address = 5000

RAM accesses location 5000

Main Functions

  • Address Translation: Converts logical address → physical address.
  • Memory Protection: Prevents one process from accessing another process's memory.
  • Relocation: Allows a process to be loaded at different physical memory locations.
  • Supports Virtual Memory: Helps map virtual addresses to physical memory using techniques such as paging and segmentation.

Important Point

The CPU generates the logical address, while the MMU performs the address translation.

Non-Contiguous Memory Allocation

Non-contiguous allocation is a memory allocation technique where a process is divided into multiple parts and these parts can be stored at different locations in physical memory.

The process does not need one continuous block of memory.

Types

  1. Paging
    • Process is divided into fixed-size pages.
    • Physical memory is divided into fixed-size frames.
    • Pages can be placed in any available frames.
    • Eliminates external fragmentation.
  2. Segmentation
    • Process is divided into logical segments such as code, data, and stack.
    • Segments can have different sizes.
    • Can cause external fragmentation.
  3. Segmentation with Paging
    • Combines segmentation and paging.
    • Each segment is further divided into pages.

Advantages

  • Better memory utilization.
  • Process does not require contiguous memory.
  • Supports virtual memory.
  • Paging eliminates external fragmentation.

Disadvantages

  • More complex than contiguous allocation.
  • Requires additional structures such as page tables/segment tables.
  • Address translation adds overhead.

Paging

  • Paging is a non-contiguous memory management technique in which a process is divided into fixed-size blocks called pages, while physical memory is divided into equal-size blocks called frames.
  • Page size = Frame size
  • Pages of a process can be stored in any available frames.
  • A process does not need contiguous physical memory.
  • Only required pages may be loaded into RAM, supporting virtual memory.

Why Do We Need Paging?

Without paging, a process needs a contiguous block of memory, which can cause external fragmentation.

Paging solves this by:

  • Allowing pages to be placed anywhere in RAM.
  • Eliminating external fragmentation.
  • Supporting execution of programs larger than available physical memory through virtual memory.
  • Making memory allocation easier using fixed-size pages and frames.
  • Logical Address Space or Virtual Address Space: The Logical Address Space, refers to the set of all possible logical addresses that a process can generate during its execution.
  • Physical Address Space: The Physical Address Space refers to the total range of addresses available in a computer's physical memory (RAM).

Page Table

A data structure maintained by the OS that maps page numbers to frame numbers.

Basic Paging Structure

Logical Address = [ Page Number | Page Offset ]
Page Table:
Page Number → Frame Number
Physical Address = [ Frame Number | Frame Offset ]

Since page size and frame size are equal:

Page Offset = Frame Offset

Logical Address

A logical address is divided into:

Logical Address = Page Number + Page Offset

Where:

  • p = Page number
  • d = Page offset

Physical Address

A physical address is divided into:

Physical Address = Frame Number + Frame Offset

Where:

  • f = Frame number
  • d = Frame offset

Address Translation

Suppose the CPU generates:

Logical Address = (Page Number, Offset)

The MMU:

  1. Extracts the page number.
  2. Uses the page number to access the page table.
  3. Finds the corresponding frame number.
  4. Combines the frame number with the same offset.
  5. Generates the physical address.

Page Number → Page Table → Frame Number

Address Translation

Page Table Base Register — PTBR

PTBR (Page Table Base Register) contains the physical address of the first entry/start of the page table.

When a process is switched:

  • OS loads the corresponding page table address into the PTBR.
  • MMU uses PTBR to locate the page table.

Important:

PTBR stores the address of the page table, not the page number.

Effective Access Time with and without PTBR

PTBR (Page Table Base Register) stores the starting physical address of the page table.

Without PTBR

If the page table is stored in main memory, but there is no PTBR, the system needs an extra mechanism/register to locate the page table. Conceptually, the access still requires:

  1. Access page table.
  2. Access actual data/instruction.

If main memory access time = m:

EAT = m + m = 2m

With PTBR

PTBR directly contains the base address of the page table.

However, PTBR does not eliminate the page-table memory access.

For every memory reference:

  1. PTBR gives the location of the page table.
  2. Access page table → m
  3. Access actual data → m

Therefore:

EAT = 2m

Paging with TLB

TLB (Translation Lookaside Buffer) is a small, fast cache that stores recently used page number → frame number mappings.

It reduces the time required to access the page table in main memory.

Paging with TLB

Working

CPU generates:

Logical Address = Page Number + Offset

Then:

  1. CPU sends the page number to TLB.
  2. TLB Hit: Page number is found → frame number is obtained directly.
  3. TLB Miss: Page number is not found → page table in main memory is accessed.
  4. Frame number + offset gives the physical address.
  5. Actual data is accessed from RAM.

TLB Hit

CPU → TLB → Physical Memory

If:

  • TLB lookup = t
  • Memory access = m

Then:

Time = t + m

TLB Miss

CPU → TLB → Page Table → Physical Memory

Time:

Time = t + m + m

Time = t + 2m

Effective Access Time (EAT)

If:

  • α = TLB hit ratio
  • t = TLB lookup time
  • m = main memory access time

Then:

EAT = α(t + m) + (1 − α)(t + 2m)

Simplified:

EAT = t + m + (1 − α)m

Important Interview Point

PTBR is used to locate the page table; it is not a cache.

TLB is what reduces the extra page-table lookup.

Page Table Entry (PTE)

Page Table Entry (PTE) is an entry in the page table that stores information needed to map a virtual page/logical page to a physical frame and control access to that page.

Page Table Entry (PTE)

Information Stored in PTE

1. Frame Number

  • Identifies the physical frame where the page is stored.
  • Frame number bits:

Frame Number Bits = log₂(Physical Memory / Frame Size)

2. Present / Absent Bit

  • Tells whether the page is currently in RAM.
  • 1 → Page is present
  • 0 → Page is absent → Page Fault

3. Protection Bits

  • Specify allowed operations:
    • R → Read
    • W → Write
    • X → Execute
  • Prevent unauthorized memory access.

4. Referenced / Accessed Bit

  • Set when the page is accessed.
  • Used by page replacement algorithms such as LRU/Clock.

5. Cache Bit

  • Determines whether caching is enabled for the page.
  • Useful for memory-mapped I/O, where fresh values may be required.

6. Dirty / Modified Bit

  • Indicates whether the page has been modified after being loaded into RAM.
  • Dirty = 1: Page must generally be written back before replacement.
  • Dirty = 0: Page can generally be discarded without writing it back.

Basic Paging Structure

Logical Address = [ Page Number | Page Offset ]
Page Table:
Page Number → Frame Number
Physical Address = [ Frame Number | Frame Offset ]

Since:

Page Size = Frame Size

Therefore:

Page Offset = Frame Offset

Important Address Terms

Logical Address (LA)

Number of bits required to represent one logical address.

Physical Address (PA)

Number of bits required to represent one physical address.

Logical Address Space (LAS)

Total size of the logical/virtual address space of a process, measured in bytes.

LAS = 2^LA bytes

Physical Address Space (PAS)

Total size of the physical memory, measured in bytes.

PAS = 2^PA bytes

LA vs LAS

TermMeaningUnit
LABits required to represent one logical addressBits
LASTotal logical address spaceBytes

LAS = 2^LA

Example:

LA = 32 bits

LAS = 2³² bytes = 4 GB

PA vs PAS

TermMeaningUnit
PABits required to represent one physical addressBits
PASTotal physical address spaceBytes

PAS = 2^PA

Example:

PA = 32 bits

PAS = 2³² bytes = 4 GB

Number of Pages

If:

  • LAS = Logical Address Space
  • PS = Page Size
  • p = Page number bits

Then:

Number of Pages = LAS / PS

Since:

LAS = 2^LA

and

PS = 2^d

Therefore:

Number of Pages = 2^(LA − d)

Hence:

p = LA − d

or:

2^p = LAS / PS

Number of Frames

If:

  • PAS = Physical Address Space
  • FS = Frame Size
  • f = Frame number bits

Then:

Number of Frames = PAS / FS

Since:

PAS = 2^PA

and:

FS = PS = 2^d

Therefore:

Number of Frames = 2^(PA − d)

Hence:

f = PA − d

or:

2^f = PAS / FS

Address Format

Logical address:

LA = p + d

where:

  • p = Page number bits
  • d = Page offset bits

Physical address:

PA = f + d

where:

  • f = Frame number bits
  • d = Frame offset bits

Therefore:

Page Offset Bits = Frame Offset Bits

Number of Entries in Page Table

Each process has one page table.

Number of PTEs = Number of Pages

Therefore:

Number of PTEs = 2^p

Page Table Entry Size

A PTE must contain the frame number.

Therefore:

PTE Size = Number of bits required to represent a frame

PTE Size = f bits

But remember: if the question asks for PTE size in bytes, convert:

PTE Size = f / 8 bytes

Page Table Size

Page Table Size = Number of Pages × PTE Size

If PTE is given in bits:

PT Size = 2^p × f bits

If PTE is given in bytes:

PT Size = 2^p × PTE Size bytes

Average Internal Fragmentation

For fixed-size pages:

Average Internal Fragmentation ≈ Page Size / 2

More precisely, assuming random process size:

Average Internal Fragmentation = (Page Size − 1) / 2

For large page sizes, this is approximately:

Average Internal Fragmentation ≈ 50% of Page Size

Example:

Page Size = 4 KB

Average Internal Fragmentation ≈ 2 KB

TLB Access Time

Let:

  • t = TLB lookup time
  • m = main memory access time
  • α = TLB hit ratio

TLB Hit:

Time = t + m

TLB Miss:

Time = t + 2m

Effective Access Time:

EAT = α(t + m) + (1 − α)(t + 2m)

Simplified:

EAT = t + m + (1 − α)m

Without TLB

Page table is in main memory.

EAT = 2m

Because:

  1. Access page table.
  2. Access actual data/instruction.

Multilevel Paging

If the page table itself becomes too large, we divide it into multiple levels.

First calculate:

Entries per Page = Page Size / PTE Size

If:

  • Page Size = 2^d
  • PTE Size = 2^e

Then:

Entries per Page = 2^(d−e)

Therefore:

Bits represented by each level = log₂(Entries per Page)

Bits per Level = d − e

Finding Number of Levels

First calculate:

Page Number Bits = LA − Page Offset Bits

Then:

Number of Levels = ⌈Page Number Bits / Bits per Level⌉

Therefore:

Number of Levels = ⌈(LA − d) / log₂(Page Size / PTE Size)⌉

Finding Outer Page Table

Suppose the first-level page table requires:

2^m pages

Then the outer page table needs:

2^m entries

Therefore:

Outer Page Table Size = 2^m × PTE Size

If PTE size is f bits:

Outer PT Size = 2^m × f bits

To find how many pages are required for the outer page table:

Pages Required = Outer PT Size / Page Size

Quick Multilevel Paging Shortcut

Use this order:

1. Find Offset Bits

2. Find Page Number Bits

3. Find Entries Per Page

4. Find Bits Per Level

5. Divide Page Number Bits by Bits Per Level

6. Ceiling → Number of Levels

Formula:

Offset = log₂(Page Size)

Page Bits = LA − Offset

Entries/Page = Page Size / PTE Size

Bits/Level = log₂(Entries/Page)

Levels = ⌈Page Bits / Bits/Level⌉

EAT for Multilevel Paging

If there are n levels of page tables and each memory access takes m:

EAT = (n + 1)m

Because:

  • n memory accesses → page-table levels
  • 1 memory access → actual data

Example:

2-level paging:

EAT = (2 + 1)m = 3m

3-level paging:

EAT = (3 + 1)m = 4m

With a TLB, a TLB hit can avoid the page-table walks, while a TLB miss requires the page-table levels to be accessed.

Multilevel Paging

Multilevel paging is a technique in which the page table itself is divided into multiple levels, so that the entire page table does not need to be stored as one large contiguous block.

Why Do We Need Multilevel Paging?

In a simple paging system, every process needs a page table.

For a large process, the page table can become very large.

Example:

  • Process Size = 16 MB = 2²⁴ bytes
  • Page Size = 1 KB = 2¹⁰ bytes
  • PTE Size = 4 bytes

Step 1: Number of Pages

Number of Pages = Process Size / Page Size

= 2²⁴ / 2¹⁰

= 2¹⁴ = 16,384 pages

Therefore, the page table needs 16,384 PTEs.

Step 2: Size of Page Table

Page Table Size = Number of Pages × PTE Size

= 16,384 × 4

= 65,536 bytes = 64 KB

So, the page table itself is 64 KB.

Now page table size > frame size so how we can store this in main memory so we need to divided page table into multiple pages

Multilevel paging solves this problem by paging the page table itself.

How Multilevel Paging Works

Instead of:

One large page table

we create:

Outer Page Table → Inner Page Tables → Frames

The outer page table contains pointers to inner page tables.

Only the required inner page tables need to be created.

How Multilevel Paging Works

Step 3: Entries Per Page

Each page/frame is 1 KB = 1024 bytes.

Each PTE = 4 bytes.

Therefore:

Entries per Page = Page Size / PTE Size

= 1024 / 4

= 256 = 2⁸ entries

So, one page can hold 256 PTEs.

Step 4: Number of Inner Page Tables

Total PTEs:

16,384 = 2¹⁴

Each inner page table can contain:

256 = 2⁸ PTEs

Therefore:

Number of Inner Page Tables = 2¹⁴ / 2⁸

= 2⁶ = 64

So we need 64 inner page tables.

Each inner page table occupies 1 KB.

Step 5: Outer Page Table

The outer page table needs 64 entries, one for each inner page table.

Each entry is 4 bytes:

Outer Page Table Size = 64 × 4

= 256 bytes

Since:

256 bytes < 1 KB

the outer page table fits inside one page/frame.

Segmentation

Segmentation is a memory management technique in which a process is divided into variable-sized units called segments, where each segment represents a logical part of a program such as functions, arrays, or modules.

It follows the user’s logical view of memory

segmentation divides a process based on its logical structure, not into equal-sized blocks.

Why Do We Need Segmentation?

Paging divides a process into fixed-size pages, but it does not represent the logical structure of a program.

Why Do We Need Segmentation?

Segments can have different lengths, depending on the program’s requirements.

Segments represent meaningful units like code, stack, data, or modules

Logical Address in Segmentation

A logical address is divided into:

Logical Address = Segment Number + Offset

For example:

(Segment 2, Offset 500)

means:

Go to Segment 2 and access the location 500 bytes from its beginning.

Segment Table

The OS maintains a Segment Table.

Each segment-table entry typically contains:

  • Base → Starting physical address of the segment.
  • Limit → Size/length of the segment.
  • Protection bits → Read/Write/Execute permissions.

Address Translation

CPU generates:

Segment Number + Offset

The MMU:

  1. Uses the segment number to access the segment table.
  2. Gets Base and Limit.
  3. Checks:

Offset < Limit

  1. If valid:

Physical Address = Base + Offset

  1. If Offset ≥ Limit:

Segmentation Fault

Address Translation
Address Translation

Advantages

Represents the logical structure of a program.

Easy to provide different protection levels to different segments.

Segments can grow independently.

Supports sharing of logical program components.

Disadvantages

Segments are variable-sized, causing external fragmentation.

Memory allocation is more complex.

May require compaction.

Segmentation vs Paging

FeaturePagingSegmentation
DivisionFixed-size pagesVariable-size segments
Based onPhysical memory managementLogical program structure
AddressPage + OffsetSegment + Offset
FragmentationInternalExternal
ExamplePage 5Code segment
Programmer viewUsually invisibleLogical structure is visible

Why Segmentation Instead of Only Paging?

Paging focuses on efficient physical memory allocation, while segmentation focuses on the logical organization and protection of a program.

Segmentation with Paging

Segmentation with paging is a memory management technique that combines both segmentation and paging to overcome their individual limitations.

It solves some limitations of using only segmentation or only paging.

Why Do We Need Segmentation with Paging?

Problem with Segmentation:

  • Segments are variable-sized.
  • Can cause external fragmentation.
  • Large segments can be difficult to allocate contiguously.

Problem with Paging:

  • Pages are fixed-sized.
  • Paging does not naturally represent the logical structure of a program.

Therefore:

Segmentation → Logical View

Paging → Efficient Physical Memory Allocation

Basic Structure

A process is divided into segments.

Each segment is further divided into pages.

Physical memory is divided into frames.

Process
├── Segment 0
│   ├── Page 0
│   └── Page 1
├── Segment 1
│   ├── Page 0
│   └── Page 1
└── Segment 2
    ├── Page 0
    └── Page 1

Pages map to physical frames.

Logical Address

The logical address is divided into:

[ Segment Number | Page Number | Page Offset ]

Where:

  • Segment Number (s) → identifies the segment.
  • Page Number (p) → identifies the page within that segment.
  • Offset (d) → identifies the exact location within the page.

Address Translation

CPU generates:

Segment Number + Page Number + Offset

Then:

Step 1: Segment number is used to access the segment table.

Step 2: Segment table gives the address of the page table for that segment.

Step 3: Page number is used to access that page table.

Step 4: Page table gives the frame number.

Step 5: Frame number + offset gives the physical address.

CPU
↓
Segment Number
↓
Segment Table
↓
Page Table
↓
Frame Number
↓
Physical Memory

Important Formula

If:

  • Page size = 2ᵈ bytes

Then:

Offset bits = d

If logical address size = m bits:

Segment Bits + Page Number Bits + Offset Bits = m

Overlays in Memory Management

Overlay is a memory-management technique where only the required part of a program is loaded into main memory, while other parts remain on secondary storage and are loaded when needed.

It was mainly used when physical memory was smaller than the size of the complete program.

Why Do We Need Overlays?

Suppose:

Program size = 20 MB

Available RAM = 10 MB

The entire program cannot fit into RAM.

With overlays, the program is divided into modules:

Main program
├── Module A
├── Module B
└── Module C

Only the modules required at a particular time are loaded into RAM.

For example:

RAM
┌──────────────┐
│ Main program │
│ Module A     │
└──────────────┘

Later:

RAM
┌──────────────┐
│ Main program │
│ Module B     │
└──────────────┘

Module A can be replaced by Module B because they are not needed simultaneously.

How Overlays Work

  1. Divide the program into smaller modules.
  2. Identify modules that are not required simultaneously.
  3. Keep only the required modules in RAM.
  4. When another module is required, load it into the overlay area.
  5. The new module replaces the previous module.

Virtual Memory

9. Virtual Memory, Demand Paging & Page Replacement

Virtual Memory is a memory-management technique that allows a process to execute even when the entire process is not loaded into physical RAM.

It uses secondary storage (disk/SSD) as an extension of RAM and loads required parts of a process into memory on demand.

Why Do We Need Virtual Memory?

Suppose:

Process size = 10 GB

Available RAM = 4 GB

Normally, the entire process cannot fit into RAM.

With virtual memory:

Only the required pages are loaded into RAM.

The remaining pages stay on disk until they are needed.

Virtual Memory vs Overlay

Both allow a program larger than RAM to execute, but the major difference is who manages what gets loaded into memory.

FeatureOverlayVirtual Memory
Managed byProgrammerOS + Hardware
LoadingProgrammer explicitly loads modulesOS automatically loads pages
UnitModules/parts of programPages (or segments)
Address translationNot necessarily requiredRequired
Page faultNoYes
Memory protectionLimitedSupported
Programmer involvementHighVery low
Modern systemsRare/mostly obsoleteWidely used

How Virtual Memory Works

  1. CPU generates a virtual/logical address.
  2. MMU translates it using the page table.
  3. If the required page is in RAM:
    • Access continues normally.
    • This is a page hit.
  4. If the page is not in RAM:
    • A page fault occurs.
  5. OS loads the required page from disk into a free frame.
  6. Page table is updated.
  7. The interrupted instruction is restarted.

Page Fault

Occurs when the required page is not present in RAM.

Demand Paging

Pages are loaded into RAM only when they are actually needed.

Swap Space

Disk/SSD area used to temporarily store memory pages that are not currently in RAM.

Virtual Memory vs Physical Memory

Virtual MemoryPhysical Memory
Logical/virtual address spaceActual RAM
LargerLimited
Managed by OS + MMUActual hardware memory
Uses pagesUses frames
Can use disk as backing storeFaster than disk

Types of Virtual Memory

Virtual memory can be implemented mainly using:

  1. Paging
  2. Segmentation

The MMU (Memory Management Unit) translates virtual addresses generated by the CPU into physical addresses.

1. Paging

Paging divides virtual memory into fixed-size pages and physical memory into equal-size frames.

Only required pages are loaded into RAM. Pages not currently in memory remain in secondary storage.

Virtual Memory
Pages
↓
Page Table
↓
Physical Memory
Frames

Key points:

  • Page = fixed-size block of virtual memory.
  • Frame = fixed-size block of physical memory.
  • Page Size = Frame Size
  • Page table maps Page → Frame.
  • If required page is not in RAM → Page Fault.
  • OS loads the page from secondary storage into RAM.

Page Fault Service Time

Page Fault Service Time (s) = total time required to handle a page fault and make the required page available in RAM.

If:

  • m = normal memory access time
  • s = page fault service time
  • p = page fault rate

Then:

EAT = (1 − p)m + ps

or

EAT = m + p(s − m)

Important: This simplified formula assumes s already includes the required page-fault handling and memory access overhead.

2. Segmentation

Segmentation divides virtual memory into variable-sized logical segments.

Examples:

  • Code
  • Data
  • Stack
  • Heap

Each segment can be loaded into memory when required.

Virtual Memory
↓
+---------+
| Code |
| Data |
| Stack |
| Heap |
+---------+
↓
Segment Table
↓
Physical Memory

Key points:

  • Segments are variable-sized.
  • Segment table stores information such as:
    • Base address
    • Limit
    • Protection
    • Present/valid information
  • Required segments can be brought into memory when needed.

Demand Paging

Demand Paging is a virtual-memory technique in which a page is loaded into RAM only when it is actually required by the CPU.

Unlike loading the complete process into memory, demand paging loads pages on demand.

Pure Demand Paging

Pure Demand Paging means a process starts execution with none of its pages loaded into RAM.

The first time a page is referenced:

Page Fault → OS loads the page → Execution continues

After some pages have been loaded, subsequent references to those pages can execute without a page fault.

Key point:

Pure demand paging may cause many page faults when a process starts because initially no pages are in memory.

Working Process of Demand Paging

CPU generates a virtual address
└── Check the page table
    ├── Page present → Access RAM
    └── Page absent → Page fault
        ├── Invalid reference → Raise an exception
        └── Valid reference
            1. Obtain a frame, replacing a page if necessary.
            2. Load the required page.
            3. Update the page table.
            4. Restart the instruction.

Steps

  1. CPU references a page.
  2. MMU checks the page table.
  3. Present bit = 1 → page is already in RAM.
  4. Present bit = 0 → page fault occurs.
  5. OS checks whether the memory reference is valid.
  6. OS finds a free frame.
  7. Required page is loaded from secondary storage.
  8. Page table is updated.
  9. Present bit is set to 1.

10. Faulting instruction is restarted.

What Happens If No Free Frame Exists?

If RAM has no free frame:

Page Replacement Algorithm is used.

The OS selects a victim page and replaces it with the required page.

Common algorithms:

  • FIFO
  • LRU
  • LFU
  • MRU
  • Random

How Demand Paging Affects Performance

Demand paging improves memory utilization, but page faults are expensive.

Normal memory access:

RAM → Fast

Page fault:

RAM → Disk/SSD → RAM → Continue execution

Therefore:

Page fault time ≫ Memory access time

Even a small page-fault rate can significantly increase the effective access time.

Effective Access Time

If:

  • m = normal memory access time
  • s = page-fault service time
  • p = page-fault rate

Then:

EAT = (1 − p)m + ps

or:

EAT = m + p(s − m)

If p increases significantly:

EAT increases → System performance decreases

Factors Affecting Demand Paging Performance

  • Page fault rate
  • Page fault service time
  • Memory access time
  • Page replacement algorithm
  • Number of available frames
  • Disk/SSD speed
  • Locality of reference

Demand Paging vs Pre-Paging

FeatureDemand PagingPre-Paging
LoadingLoads page when neededLoads pages before they are needed
Main ideaJust in timeLoad in advance
Initial page faultsMore likelyCan reduce them
Memory usageGenerally lowerCan be higher
RiskMore page faultsMay load unnecessary pages
Best whenAccess pattern is unpredictablePages have strong locality

Page Fault

A page fault occurs when a process references a virtual page that is not currently available in the required physical memory location.

It is a trap to the operating system, which then decides how to handle the reference.

Causes of Page Fault

1. Demand Paging

  • Required page is not currently in RAM.
  • OS loads it from secondary storage.

2. Invalid Memory Access

  • Process accesses an address outside its valid address space.
  • Example: accessing memory that was never allocated.

3. Protection Violation

  • Process accesses a page in an unauthorized way.
  • Example: trying to write to a read-only page.

Types of Page Fault

1. Minor Page Fault

Required data is already available in physical memory, so no disk I/O is required.

Example: The page may already be in RAM but needs to be mapped into the process's address space.

2. Major Page Fault

Required page is not in RAM and must be fetched from secondary storage.

This is expensive because it involves I/O.

3. Invalid Page Fault

Process makes an invalid memory reference or violates memory protection.

The OS generally terminates the process or raises an appropriate exception.

Steps in Page Fault Handling

  1. CPU generates a virtual address.
  2. MMU checks the page table.
  3. Present bit = 0 → page fault occurs.
  4. Control transfers to the OS.
  5. OS checks whether the memory reference is valid.
  6. If invalid → process gets an exception/termination.
  7. If valid → OS finds a free frame.
  8. If no free frame exists → page replacement is performed.
  9. Required page is read from secondary storage.

10. Page table is updated.

11. Present bit is set.

12. Faulting instruction is restarted.

Impact on Performance

Page faults are expensive because:

Disk/SSD access ≫ RAM access

Frequent page faults can cause:

Increased Latency

  • Processes spend more time waiting for I/O.

Reduced CPU Utilization

  • CPU may remain idle while waiting for page I/O.

Thrashing

  • Excessive page faults cause the system to spend more time swapping/pages handling than executing processes.

Important Interview Point

Not every page fault requires disk access.

  • Minor fault → usually no disk I/O.
  • Major fault → disk/secondary-storage I/O required.
  • Invalid fault → invalid/protected memory access.

Swap Space

Swap space is a portion of secondary storage (usually disk/SSD) used by the operating system to temporarily store pages or memory contents that are not currently needed in RAM.

It acts as a backing store for virtual memory.

Why Do We Need Swap Space?

RAM is limited.

When RAM becomes heavily occupied, the OS can move less-used pages from RAM to swap space:

RAM → Swap Space

When the page is needed again:

Swap Space → RAM

This frees RAM for other processes.

Swap Out

Moving a page/process from RAM to secondary storage.

RAM → Disk

Swap In

Bringing a page/process back from secondary storage into RAM.

Disk → RAM

Swap Space and Page Fault

Suppose a page was previously moved to swap:

  1. Process references the page.
  2. Page is not present in RAM.
  3. Page fault occurs.
  4. OS finds the page in swap space.
  5. Page is loaded into a physical frame.
  6. Page table is updated.
  7. Instruction is restarted.

Swap Space vs Page File

Conceptually they serve the same purpose, but terminology differs by OS:

  • Linux/Unix: Usually called swap space and can be a swap partition or swap file.
  • Windows: Uses a page file.

Page Replacement Algorithms

Page replacement is required when a page fault occurs and there is no free frame in RAM.

The OS must choose a victim page to remove and replace it with the required page.

Page Replacement Steps

  1. Page fault occurs.
  2. Check for a free frame.
  3. If no free frame exists, select a victim page.
  4. If victim page is dirty, write it back to disk.
  5. Load the required page into the freed frame.
  6. Update the page table.
  7. Restart the interrupted instruction.

Common Algorithms

  1. FIFO — First In First Out
  2. Optimal
  3. LRU — Least Recently Used
  4. MRU — Most Recently Used

1. FIFO

Replace the page that entered memory first.

Think of it as a queue:

First In → First Out

Advantages:

  • Very simple.
  • Easy to implement using a queue.

Disadvantage:

  • May remove an important frequently used page.
  • Can suffer from Belady's Anomaly.

2. Optimal Page Replacement

Replace the page that will not be used for the longest time in the future.

Advantages:

  • Produces the minimum possible number of page faults.
  • Used as a benchmark for other algorithms.

Disadvantage:

  • Cannot be implemented practically because the OS does not know future page references.

Optimal = Best theoretical algorithm

3. LRU

Replace the page that has not been used for the longest time in the past.

Advantages:

  • Generally performs well.
  • Based on locality of reference.
  • Does not suffer from Belady's Anomaly.

Disadvantage:

  • Tracking exact usage history can be expensive.

LRU = Look backward

4. MRU

Replace the page that was used most recently.

Disadvantage:

  • Usually performs worse than LRU for typical workloads.
  • Can suffer from Belady's Anomaly.

MRU = Remove the most recently used page

Quick Comparison

AlgorithmVictim PageFuture KnowledgeBelady's Anomaly
FIFOOldest pageNoYes
OptimalUsed farthest in futureYesNo
LRULeast recently usedNoNo
MRUMost recently usedNoCan occur

Belady's Anomaly

Belady's Anomaly is a phenomenon where increasing the number of page frames causes the number of page faults to increase instead of decrease.

Normally:

More Frames → Fewer Page Faults

But during Belady's Anomaly:

More Frames → More Page Faults

Why Does It Happen?

It occurs in some non-stack page replacement algorithms, where increasing the number of frames can change the replacement order in an unfavorable way.

The most famous example is:

FIFO

Belady's Anomaly in FIFO

Reference String:

1 2 3 4 1 2 5 1 2 3 4 5

Using FIFO:

FramesPage Faults
39
410

So:

3 frames → 9 faults

4 frames → 10 faults

Even though we increased the number of frames, page faults increased.

This is Belady's Anomaly.

Stack Property

A stack algorithm has the property that:

Pages present with N frames are always a subset of pages present with N+1 frames.

Therefore:

Increasing frames cannot increase page faults.

Examples:

  • LRU
  • Optimal

These do not suffer from Belady's Anomaly.

Why FIFO Suffers

FIFO only considers:

When was the page loaded?

It does not consider whether the page is frequently used.

Therefore, increasing the number of frames can change the FIFO replacement order and cause a useful page to be removed.

Algorithms and Belady's Anomaly

AlgorithmBelady's Anomaly
FIFOYes
OptimalNo
LRUNo
Second ChanceCan occur
RandomCan occur
LFUDepends on implementation; not generally guaranteed to be anomaly-free

Important Correction

Do not memorize:

“LFU is always a stack algorithm.”

The safe interview answer is:

“Stack algorithms such as LRU and Optimal do not suffer from Belady's Anomaly.”

Thrashing

Thrashing occurs when the OS spends more time handling page faults and swapping pages between RAM and disk than executing processes.

Thrashing

Cycle of Thrashing:

  • High multiprogramming: Too many processes are loaded into memory.
  • Insufficient frames: Each process receives fewer memory frames than required.
  • Frequent page replacement: More page faults lead to continuous swapping between memory and disk.

This repeated cycle of low CPU utilization -> more processes -> more page faults is called Thrashing.

Role of Locality of Reference

Locality of reference means a process tends to access a small group of pages repeatedly during a period of time.

This group is called the working locality.

How to Control Thrashing

  1. Reduce degree of multiprogramming
  2. Allocate more frames
  3. Use Working Set Model
  4. Use Page Fault Frequency
  5. Suspend some processes if necessary

Working Set Model

The Working Set Model keeps enough pages in memory to support the process's current locality.

Let:

  • WSSᵢ = Working Set Size of process i
  • Δ = Working-set window
  • D = Total memory demand
  • m = Total available frames

Formula:

D = Σ WSSᵢ

If:

D > m → Thrashing

If:

D ≤ m → No thrashing

Example:

P1 WSS = 4 frames

P2 WSS = 5 frames

P3 WSS = 3 frames

D = 4 + 5 + 3 = 12 frames

If available frames:

m = 10

Then:

D > m → Thrashing

Page Fault Frequency (PFF)

PFF controls thrashing by monitoring the page-fault rate.

Page-fault rate
├── Above upper limit → Allocate more frames
├── Within limits     → Keep the current allocation
└── Below lower limit → Reclaim some frames
  • Fault rate > upper limit → Allocate more frames.
  • Fault rate < lower limit → Remove/reallocate some frames.
  • No available frames → Suspend a process and give its frames to others.

Memory Interleaving

Memory interleaving is a technique that divides main memory into multiple independent banks so that consecutive memory accesses can be handled in parallel or overlapped, increasing memory bandwidth.

Why Is It Needed?

A single memory bank can become a bottleneck because the CPU may have to wait for one memory operation to finish.

With multiple banks:

Multiple memory operations can be overlapped → Higher memory performance

How It Works

Suppose memory has 4 banks:

Address 0 → Bank 0
Address 1 → Bank 1
Address 2 → Bank 2
Address 3 → Bank 3
Address 4 → Bank 0
Address 5 → Bank 1
...

So consecutive addresses are distributed across different banks.

Types

1. Low-Order Interleaving

Lower-order address bits select the memory bank.

Address → Bank
0 → 0
1 → 1
2 → 2
3 → 3
4 → 0
  • Consecutive addresses go to different banks.
  • Good for sequential memory access.

2. High-Order Interleaving

Higher-order address bits select the memory bank.

Large contiguous block → Bank 0
Next block → Bank 1
Next block → Bank 2
  • Consecutive addresses within a block remain in the same bank.
  • Useful when accesses are localized within blocks.

Quick Comparison

FeatureLow-OrderHigh-Order
Bank selectionLower address bitsHigher address bits
Consecutive addressesDifferent banksUsually same bank
Good forSequential accessBlock/localized access

Key Point

Memory interleaving improves memory throughput, not necessarily the latency of a single memory access.

10. File Systems & Storage Organization

File System in Operating System

A file system is a method used by the OS to organize, store, name, access, and manage files and directories on storage devices.

Why Do We Need a File System?

  • Organize files and directories.
  • Provide easy file access.
  • Manage storage space.
  • Track file locations.
  • Provide file protection and permissions.
  • Support file creation, deletion, reading, and writing.

Basic File System Structure

User
↓
Application
↓
File System
↓
Storage Management
↓
Disk / SSD

File

A file is a named collection of related data stored on secondary storage.

Common file types:

  • Text files
  • Executable files
  • Images
  • Videos
  • Documents

Directory

A directory is a data structure used to organize and locate files.

Example:

/home/dilip/
├── resume.pdf
├── notes.txt
└── projects/
    ├── app.cpp
    └── README.md

Main Functions of File System

  1. File Creation
  2. File Deletion
  3. Read / Write
  4. File Naming
  5. Directory Management
  6. Space Management
  7. File Protection
  8. File Access Control

File Attributes

A file generally has:

  • Name
  • Type
  • Size
  • Location
  • Owner
  • Permissions
  • Creation/modification time

File Operations

Common operations:

Create

Open

Read

Write

Seek

Close

Delete

File System Examples

File SystemCommon Usage
FAT32USB drives, older systems
NTFSWindows
ext4Linux
APFSmacOS
XFSLinux/servers

Important Interview Point

File System ≠ Storage Device

A storage device provides physical storage, while the file system determines how the OS organizes and accesses data on that storage.

Linux File System

Linux uses a hierarchical file system where everything starts from the root directory /.

Linux File System Structure

/
├── bin → Essential user commands
├── boot → Bootloader and kernel files
├── dev → Device files
├── etc → System configuration files
├── home → User home directories
├── lib → Essential shared libraries
├── media → Mounted removable devices
├── mnt → Temporary mount point
├── opt → Optional software
├── proc → Process and kernel information
├── root → Home directory of root user
├── run → Runtime information
├── sbin → System administration commands
├── tmp → Temporary files
├── usr → User applications and utilities
└── var → Logs, cache, variable data

Important Directories

DirectoryPurpose
/Root of entire file system
/homeUser files
/rootRoot user's home
/etcConfiguration files
/binEssential commands
/sbinSystem commands
/devDevice files
/procProcess/kernel information
/tmpTemporary files
/varLogs and changing data
/bootBoot-related files
/usrApplications and utilities

Key Linux Concept

“Everything is a file”

Linux represents many resources as files, including:

  • Regular files
  • Directories
  • Devices
  • Pipes
  • Sockets

For example:

/dev/sda

represents a storage device.

File System Hierarchy

Linux follows a tree-like hierarchical structure:

/
├── home/
│   └── dilip/
│       └── notes.txt
├── etc/
│   └── config
└── var/
    └── log/

Every file has a unique path.

Example:

/home/dilip/notes.txt

Common Linux File Systems

  • ext4 → Most commonly used Linux file system
  • XFS → High-performance/server workloads
  • Btrfs → Copy-on-write, snapshots, checksums
  • ext3/ext2 → Older Linux file systems

Inode

An inode stores metadata about a file, but normally does not store the file name or file data itself.

It contains information such as:

  • File type
  • File permissions
  • Owner
  • File size
  • Timestamps
  • Links
  • Pointers to data blocks

Think:

File name → inode → data blocks

Path Name in File Directory

A path name is the location of a file or directory in the file system. It tells the OS how to reach that file from a particular starting point.

Types of Path Names

1. Absolute Path

Starts from the root directory / and gives the complete path.

Example:

/home/dilip/projects/app.cpp

  • Always starts with /.
  • Does not depend on the current directory.
  • Uniquely identifies the location.

2. Relative Path

Specifies the location relative to the current working directory.

Suppose current directory is:

/home/dilip/projects

Then:

./app.cpp

or

../notes.txt

  • . → Current directory
  • .. → Parent directory

Absolute vs Relative Path

FeatureAbsolute PathRelative Path
Starts fromRoot /Current directory
Depends on current directoryNoYes
Example/home/dilip/a.txt../a.txt
LengthUsually longerUsually shorter

Path Example

/home/dilip/projects/app.cpp

/                   Root directory
└── home/           Home directories
    └── dilip/      User's home directory
        └── projects/
            └── app.cpp  File

Special Path Symbols

SymbolMeaning
/Root directory
.Current directory
..Parent directory
~Current user's home directory

Structures of Directory in Operating System

Directory structure defines how files and directories are organized and accessed by the operating system.

1. Single-Level Directory

All files are stored in one directory.

Directory
├── file1.txt
├── file2.txt
└── file3.txt

Advantages:

  • Very simple.
  • Easy to implement.

Disadvantages:

  • File-name conflicts.
  • Difficult to organize many files.
  • Not suitable for multiple users.
1. Single-Level Directory

2. Two-Level Directory

Each user gets a separate directory.

Master directory
├── User 1/
│   ├── a.txt
│   └── b.txt
└── User 2/
    ├── a.txt
    └── b.txt

Advantages:

  • Different users can have files with the same name.
  • Better isolation between users.

Disadvantages:

  • Limited directory organization.
  • Difficult to share files between users.
2. Two-Level Directory

3. Tree-Structured Directory

Directories can contain subdirectories, forming a tree.

/
├── home
│ └── dilip
    │ ├── notes
    │ └── projects
        │ └── app.cpp
├── etc
└── var

Advantages:

  • Easy organization.
  • Supports hierarchical directories.
  • Efficient file searching.
  • Most modern OSes use this structure.

Disadvantage:

  • Sharing files between directories can be more complicated.
3. Tree-Structured Directory

4. Acyclic Graph Directory

Allows sharing of files or directories, but does not allow cycles.

In the earlier directory structures, a file could only be accessed from the directory it was stored in. The acyclic graph directory structure solves this by allowing a file or subdirectory to be shared across multiple directories using links. Changes made by one user are visible to all users sharing that file.

4. Acyclic Graph Directory
/home/user1/shared.txt ──┐
                        ├──→ Same shared file
/home/user2/shared.txt ──┘

The same file can be accessed from multiple directories using links.

Advantages:

  • Supports file/directory sharing.
  • Avoids duplicate copies.

Disadvantages:

  • More complex than a tree.
  • Need to manage links carefully.

5. General Graph Directory

Allows directories to contain links that can create cycles.

A ──→ B ──→ C
↑           │
└───────────┘

Here, a cycle can exist.

Advantages:

  • Very flexible.
  • Supports extensive sharing.

Disadvantages:

  • Searching can get stuck in cycles.
  • Garbage collection may be required.
  • More complex to manage.

Quick Comparison

StructureMain IdeaSharingCycle
Single-LevelOne directoryNoNo
Two-LevelOne directory per userLimitedNo
TreeHierarchicalLimitedNo
Acyclic GraphSharing using linksYesNo
General GraphArbitrary linksYesPossible

Easy Way to Remember

Single → One directory

Two-Level → One per user

Tree → Hierarchy

Acyclic Graph → Sharing, no cycle

General Graph → Sharing + cycles

File Allocation Methods

File allocation methods determine how the blocks of a file are stored on secondary storage.

The main methods are:

  1. Contiguous Allocation
  2. Linked Allocation
  3. Indexed Allocation

1. Contiguous Allocation

File blocks are stored in consecutive disk blocks.

File A → [10][11][12][13][14]

Advantages:

  • Very fast sequential access.
  • Very fast random access.
  • Simple implementation.

Disadvantages:

  • External fragmentation.
  • Difficult to grow a file.
  • May require compaction.

Example:

If a file needs 5 blocks and starts at block 10:

Blocks = 10, 11, 12, 13, 14

2. Linked Allocation

File blocks can be stored anywhere on the disk, with each block pointing to the next block.

[7] → [19] → [4] → [25] → NULL

Advantages:

  • No external fragmentation.
  • Files can easily grow.
  • Any free block can be used.

Disadvantages:

  • Poor random access.
  • Pointer requires extra space.
  • If a pointer is corrupted, part of the file may become inaccessible.

Best for: Sequential access.

3. Indexed Allocation

A separate index block stores pointers to all data blocks of the file.

Index block
├── Entry 0 → Data block 7
├── Entry 1 → Data block 19
├── Entry 2 → Data block 4
└── Entry 3 → Data block 25

The index block contains addresses of the file's data blocks.

Advantages:

  • Supports direct/random access.
  • No external fragmentation.
  • Files can grow easily.

Disadvantages:

  • Extra space required for index block.
  • Large files may require multiple index blocks.

Quick Comparison

FeatureContiguousLinkedIndexed
StorageConsecutiveAnywhereAnywhere
Random AccessFastSlowFast
Sequential AccessFastFastFast
External FragmentationYesNoNo
File GrowthDifficultEasyEasy
Extra Pointer SpaceNoYesYes
Main ProblemFragmentationRandom accessIndex overhead

Easy Way to Remember

Contiguous → Together

Linked → Chain

Indexed → Index points to blocks

File Access Methods in Operating System

File access methods define how a process reads and accesses data stored in a file.

The main access methods are:

  1. Sequential Access
  2. Direct (Random) Access
  3. Indexed Access

1. Sequential Access

Data is accessed in order, from beginning to end.

Block 1 → Block 2 → Block 3 → Block 4

To access Block 4, the system normally passes through the previous blocks.

Example:

  • Reading a text file line by line.
  • Playing an audio/video stream.

Advantages:

  • Simple.
  • Efficient for sequential processing.

Disadvantage:

  • Slow when you need data in the middle/end directly.

Think: Tape

2. Direct / Random Access

Any block can be accessed directly without reading previous blocks.

        ┌── Block 1
        ├── Block 2
Request ─┼── Block 5 ← Directly access
        └── Block 8

Example:

  • Database files.
  • Disk-based applications.

Advantages:

  • Fast access to a specific location.
  • Suitable for large files.

Disadvantage:

  • Requires support for locating the required block.

Think: Array

3. Indexed Access

An index stores pointers to the locations of records/blocks, allowing fast searching and access.

Index
├── Entry A → Block 2
├── Entry B → Block 7
└── Entry C → Block 15

The system first searches the index and then accesses the required block.

Advantages:

  • Fast searching.
  • Supports both sequential and direct access.
  • Useful for large files and databases.

Disadvantage:

  • Extra memory/storage is required for the index.

Quick Comparison

FeatureSequentialDirect / RandomIndexed
Access orderIn sequenceAny locationThrough index
Random accessNoYesYes
Speed for specific recordSlowFastFast
Extra index requiredNoNoYes
ExampleLog/text fileDatabase fileIndexed database

Access Method vs Allocation Method

Don't confuse these two:

File Allocation → Where are file blocks stored?

Contiguous, Linked, Indexed

File Access → How do we access those blocks?

Sequential, Direct, Indexed

11. Secondary Storage, Disk Structure & Disk Scheduling

Secondary Memory

Secondary memory is non-volatile storage used to store data and programs permanently. It has larger capacity but is slower than primary memory.

Types of Secondary Memory

Types of Secondary Memory

1. Fixed Devices

Storage devices that are normally installed inside the computer and are not frequently removed.

Examples:

  • HDD (Hard Disk Drive)
  • SSD (Solid State Drive)
  • Internal NVMe SSD

Features:

  • Large storage capacity
  • Non-volatile
  • Used for OS, applications, and user data
  • Usually faster than removable storage

2. Removable Devices

Storage devices that can be easily connected and removed from a computer.

Examples:

  • USB Flash Drive
  • Memory Card (SD/microSD)
  • External HDD/SSD
  • CD/DVD

Features:

  • Portable
  • Easy data transfer
  • Can be used across multiple computers
  • Usually connected through USB or other removable interfaces

HDD vs SSD

HDD (Hard Disk Drive) uses magnetic rotating disks, while SSD (Solid State Drive) uses flash memory and has no moving parts.

FeatureHDDSSD
TechnologyMagnetic diskFlash memory
Moving partsYesNo
SpeedSlowerFaster
Boot timeHigherLower
LatencyHigherLower
NoiseYesSilent
Power consumptionHigherLower
DurabilityLowerHigher
Cost/GBCheaperMore expensive
CapacityUsually larger/cheaperUsually smaller for same budget
Shock resistanceLowerHigher

HDD Working

CPU
↓
Disk Controller
↓
Spindle → Rotating Platter
↓
Read/Write Head
↓
Data

Data is stored magnetically on rotating platters.

SSD Working

CPU
↓
SSD Controller
↓
Flash Memory Cells
↓
Data

Data is stored electronically in NAND flash memory cells.

Interview One-Liner

“HDD stores data magnetically on rotating platters, making it cheaper but slower, while SSD uses NAND flash with no moving parts, making it much faster, more durable, and energy-efficient.”

Disk Structure

Disk structure describes how data is physically organized and accessed on a storage disk, especially an HDD.

HDD Structure

An HDD consists mainly of:

  • Platters → Circular disks where data is stored.
  • Tracks → Concentric circles on a platter.
  • Sectors → Small divisions of a track that store data.
  • Read/Write Head → Reads or writes data.
  • Spindle → Rotates the platters.
  • Cylinder → Set of tracks at the same radius across all platters.
Platter (schematic)
┌─────────────────────────┐
│  ┌───────────────────┐  │
│  │ Track             │  │
│  │ ┌───────┬───────┐ │  │
│  │ │Sector │Sector │ │  │
│  │ └───────┴───────┘ │  │
│  └───────────────────┘  │
└─────────────────────────┘
             ↑
          Spindle
HDD Structure

Important Terms

1. Platter

Circular magnetic disk used to store data.

2. Track

A circular path on the platter.

Track 0

Track 1

Track 2

Track 3

3. Sector

A track is divided into smaller units called sectors.

Traditionally:

1 sector = 512 bytes

Modern disks may also use:

4 KB sectors

4. Cylinder

A cylinder is a collection of tracks at the same position/radius on all platters.

Platter 1 → Track 5
Platter 2 → Track 5
Platter 3 → Track 5
↓
Cylinder 5

5. Read/Write Head

Moves over the platter to read or write data.

Disk Access Time

Total time required to access data from a disk starting from initial request to the completion of data transfer,

Access time = Seek time + Rotational latency + Transfer time + Overhead

Seek Time:

Time required to move the read/write head to move to track where the required data is located.

Total seekTime=No of seeks * seek time

Rotational Latency:

Time waiting for the required sector to rotate under the head.

Average rotational latency:

Average rotational latency = 1/2 × rotation time

If disk speed is RPM:

Rotation time = 60 / RPM seconds

Therefore:

Average rotational latency = 30 / RPM seconds

Transfer Time:

Time required to read/write data from disk once the read/write head is position over the correct track and correct sector.

Data transfer time = data size/transfer rate

Transfer rate = no of bytes transfer per unit time or speed at which data is transferred.

Disk Access Time

Disk Capacity Formula

For a disk:

Disk Capacity = Number of Platters × Number of Surfaces/Platter × Tracks/Surface × Sectors/Track × Bytes/Sector

But if formatting overhead is given, you need to subtract the space reserved for metadata/control information.

With Formatting Overhead

If formatting overhead is given as a percentage:

Usable Capacity = Raw Capacity × (1 − Overhead/100)

Example:

Raw capacity = 1 TB
Formatting overhead = 5%

Usable capacity = 1 TB × (1 − 5/100) = 0.95 TB

If Overhead Is Given in Bytes

If the question says X bytes of overhead per sector:

Usable Bytes/Sector = Sector Size − Overhead

So:

Usable Capacity = Platters × Surfaces × Tracks × Sectors/Track × (Sector Size − Overhead)

Example:

Sector size = 512 bytes
Overhead = 12 bytes

Usable data per sector = 512 − 12 = 500 bytes

Therefore:

Usable Capacity = Total Number of Sectors × 500 bytes

Important Interview/Exam Trick

There are two different cases:

Overhead GivenFormula
PercentageRaw Capacity × (1 − overhead%)
Bytes/sectorTotal Sectors × (Sector Size − overhead)
Total bytesRaw Capacity − overhead

Remember: If overhead is specified per sector, subtract it from the sector size before multiplying by the number of sectors.

Disk Scheduling Algorithms

Disk scheduling determines the order in which pending disk I/O requests are served to minimize head movement and improve performance.

Goals

  • Minimize seek time
  • Minimize head movement
  • Reduce response time
  • Maximize throughput
  • Provide fairness
  • Avoid starvation

1. FCFS — First Come First Serve

Services requests in the order they arrive.

50 → 82 → 170 → 43 → 140 → 24 → 16 → 190

Pros: Simple, fair, no starvation Cons: High seek time, poor performance

Remember: FCFS = Arrival order

1. FCFS — First Come First Serve

2. SSTF — Shortest Seek Time First

Always services the request closest to the current head position.

Pros: Lower average seek time, better throughput Cons: Can cause starvation of distant requests

Remember: SSTF = Nearest request first

2. SSTF — Shortest Seek Time First

3. SCAN — Elevator Algorithm

Head moves in one direction, services requests, reaches the disk end, then reverses.

Start at 50, moving toward higher track numbers.

50 → 82 → 140 → 170 → 190 → Disk end
Disk end → 43 → 24 → 16 (reverse direction)

Pros: Good throughput, more predictable than SSTF Cons: Unnecessary movement to disk end

Remember: SCAN = Go to end + Reverse

3. SCAN — Elevator Algorithm

4. C-SCAN — Circular SCAN

Head moves in one direction only. After reaching the end, it returns to the beginning and continues.

Service requests       0 → ··· → Disk end
Return without service Disk end → 0
Resume servicing       0 → ··· → Disk end

Pros: More uniform waiting time Cons: Extra movement while returning to beginning

Remember: C-SCAN = One direction + Circular return

4. C-SCAN — Circular SCAN

5. LOOK

Similar to SCAN, but the head goes only up to the last pending request, not the physical disk end.

Start at 50, moving toward higher track numbers.

50 → 82 → 140 → 170 → 190 (last request in that direction)
190 → 43 → 24 → 16 (reverse direction)

Pros: Less unnecessary movement than SCAN Cons: Waiting time can still vary

Remember: LOOK = SCAN without going to disk end

5. LOOK

6. C-LOOK

Similar to C-SCAN, but instead of going to the physical ends, it goes only to the last request, then jumps to the request at the other end.

Pros: Less movement than C-SCAN Cons: Extra circular jump; requests may wait for a cycle

Remember: C-LOOK = C-SCAN without going to disk ends

6. C-LOOK

SCAN vs LOOK

SCANLOOK
Goes to disk endGoes to last request
More head movementLess head movement
May move unnecessarilyMore efficient

C-SCAN vs C-LOOK

C-SCANC-LOOK
Goes to physical disk endGoes only to last request
Returns to beginningJumps to other end request
More movementLess movement

7. N-STEP SCAN

Divides requests into groups of N and processes one group completely before processing the next.

Main purpose: Prevent request starvation and improve fairness.

Remember: N-STEP = Divide into batches

8. F-SCAN

Uses two queues. While one queue is being serviced, new requests go into the second queue.

Queue 1 → SCAN → Complete
↓
Queue 2 → New requests

Main purpose: Prevent arm stickiness and provide fairness.

9. LIFO

Services the most recently arrived request first.

Advantage: May improve locality in some cases. Disadvantage: Old requests can suffer starvation.

10. RSS — Random Scheduling

Selects requests randomly.

Mainly useful for simulation/analysis, not practical disk scheduling.

Quick Revision Table

AlgorithmBasic IdeaStarvation
FCFSArrival orderNo
SSTFNearest requestPossible
SCANEnd → ReverseNo
C-SCANOne direction → ReturnNo
LOOKSCAN without disk endNo
C-LOOKC-SCAN without disk endsNo
N-STEP SCANProcess batchesNo
F-SCANTwo queues + SCANNo
LIFONewest firstPossible
RSSRandomUnpredictable

Most Important for Interviews

Focus mainly on:

FCFS
↓
SSTF
↓
SCAN
↓
C-SCAN
↓
LOOK
↓
C-LOOK

Easy Memory Trick

SCAN → End + Reverse

LOOK → Last Request + Reverse

C-SCAN → End + Circular Return

C-LOOK → Last Request + Circular Jump

Disk Interleaving

Disk interleaving is a technique of arranging sectors on a disk so that the CPU/controller gets enough time to process one sector before the next required sector arrives under the read/write head.

Why Is It Needed?

In older/slower disk systems, after reading one sector, the controller may not be ready to read the immediately next physical sector.

Without interleaving:

Sector 1 → read
↓
Controller not ready
↓
Sector 2 already passed
↓
Wait for another rotation

Interleaving places other sectors between consecutive logical sectors.

Example

Without Interleaving:

Physical: 1 2 3 4 5 6 7 8
Logical: 1 2 3 4 5 6 7 8

With 2:1 Interleaving:

Physical: 1 5 2 6 3 7 4 8
Logical: 1 2 3 4 5 6 7 8

After reading sector 1, the controller gets time while sectors 5 passes, then sector 2 arrives.

Types

1. 1:1 Interleaving

Logical: 1 2 3 4 5 6
Physical: 1 2 3 4 5 6

No sectors are skipped.

2. 2:1 Interleaving

One useful sector is followed by one intervening sector.

1 → 5 → 2 → 6 → 3 → 7 → 4 → 8

Key Point

Interleaving does NOT change the logical sector order. It changes their physical arrangement on the track.

Spooling in Operating System

12. I/O Systems, Spooling & Buffering

Spooling (Simultaneous Peripheral Operations Online) is a technique where data for a slow peripheral device is temporarily stored in a disk/queue so that multiple processes can share the device efficiently.

Why Do We Need Spooling?

Some I/O devices are slow and can handle only one operation at a time.

Example: Printer

Instead of making every process wait for the printer:

Process 1 ─┐
Process 2 ─┼──→ Spool Queue → Printer
Process 3 ─┘

Processes put their print jobs into the spool queue, and the printer processes them one by one.

Example

Suppose 3 processes want to print:

P1 → Job A ─┐
P2 → Job B ─┼→ Disk/Spool Queue → Printer
P3 → Job C ─┘

The processes can continue execution while the printer handles the jobs.

Key Points

  • Uses disk as temporary storage.
  • Useful for slow and shared devices.
  • Allows multiple processes to submit jobs.
  • Provides queuing of I/O requests.
  • Improves CPU/device utilization.

Common Example

Print Spooling

Print jobs are stored in a queue on disk and sent to the printer one by one.

Spooling vs Buffering

Both temporarily store data, but their purpose and storage mechanism are different.

Spooling vs Buffering
FeatureSpoolingBuffering
PurposeManage a shared slow deviceHandle speed mismatch between components
StorageUsually diskUsually RAM/main memory
Multiple jobsYesUsually data stream
Device examplePrinterKeyboard, network, disk I/O
Main conceptQueueTemporary data storage
Allows process to continueYesYes, depending on operation

Easy Example

Spooling:

P1 ─┐
P2 ─┼→ Disk Queue → Printer
P3 ─┘

Buffering:

Fast Producer → RAM Buffer → Slow Consumer

Easy Difference to Remember

Spooling = Multiple jobs waiting for one shared device

Buffering = Temporary storage to handle different speeds