Course Overview

This course provides a comprehensive study of operating system principles and concepts. Students will learn about process management, memory management, file systems, I/O device management, and deadlock handling. The course covers both theoretical foundations and practical applications, using case studies of Unix/Linux and Windows to illustrate concepts. Students will understand how operating systems manage hardware resources, provide services to application software, and ensure efficient and secure operation of computing systems. The course includes practical laboratory exercises to reinforce theoretical concepts through hands-on experience with operating system tools and commands.

Learning Outcomes

Upon completion of this course, students will be able to:

  1. Explain the functions and goals of operating systems as resource managers and extended machines
  2. Describe operating system structures, including kernel types and system layers
  3. Analyze process concepts, thread models, scheduling algorithms, and inter-process communication
  4. Evaluate memory management techniques including paging, virtual memory, and page replacement algorithms
  5. Analyze deadlock conditions, prevention, avoidance (Banker's algorithm), and detection strategies
  6. Explain input/output device management including DMA, device controllers, and disk scheduling
  7. Describe file system organization, access methods, and protection mechanisms
  8. Evaluate security threats including viruses, worms, Trojan horses, and authentication mechanisms
  9. Compare distributed operating systems with centralized systems
  10. Conduct case studies of DOS, Windows, and Unix/Linux operating systems

Unit 1: Introduction to Operating System

Teaching Hours: 2 (indicative)

History: The evolution of operating systems from simple batch systems to modern multi-user, multi-tasking systems. Early systems included GM-NAA I/O (1950s), OS/360 (1960s), Unix (1970s), Windows (1980s), and Linux (1990s). The history highlights the progression from single-tasking to multi-tasking, the development of time-sharing systems, and the open-source movement that led to Linux and modern Unix variants.

Introduction and Generation of Operating System: An operating system (OS) is system software that manages computer hardware, software resources, and provides common services for computer programs. The OS acts as an intermediary between users and computer hardware. The term "generation" refers to the evolutionary stages of OS development:

  • First Generation (1940s-1950s): No OS, direct hardware access, punch cards.
  • Second Generation (1950s-1960s): Simple batch systems, Fortran monitor systems.
  • Third Generation (1960s-1970s): Time-sharing systems, multiprogramming, Unix.
  • Fourth Generation (1980s-present): Personal computer OS (Windows, macOS), graphical user interfaces, distributed OS, mobile OS.

Objectives(Resource Manager and Extended Machine): The OS serves two primary roles:

  • Resource Manager: Manages all system resources (CPU, memory, storage, I/O devices) efficiently and fairly. The OS allocates resources to competing processes, ensures no resource conflicts, and maximizes overall system throughput.
  • Extended Machine: Provides a convenient, efficient, and user-friendly interface to the underlying hardware. Hides the complexity of hardware, provides abstraction, and makes the computer easier to use.

Function of Operating System:

  • Process management: Creating, scheduling, and terminating processes
  • Memory management: Allocating and deallocating memory space
  • File management: Organizing, storing, retrieving, and protecting files
  • I/O device management: Controlling input/output devices
  • Security and protection: Preventing unauthorized access
  • Networking: Managing network connections and communications
  • Providing user interfaces: Command-line, graphical, or touch-based

Types of Operating System:

  • Batch OS: Jobs are collected and processed in batches without user interaction. E.g., payroll processing, bank statement generation. Advantage: Efficient for repetitive tasks. Disadvantage: No user interaction, difficult to debug.
  • Time-Sharing OS: Multiple users interact with the system simultaneously by time-sharing the CPU. E.g., Unix, Linux. Advantage: Interactive, good response time. Disadvantage: Overhead of context switching, reliability concerns.
  • Real-Time OS: Strict timing constraints; must respond within guaranteed time bounds. E.g., industrial control, aircraft systems. Advantage: Predictable, reliable. Disadvantage: Limited functionality, expensive.
  • Distributed OS: Multiple independent computers appear as a single system. E.g., Linux clusters, Windows Server. Advantage: Resource sharing, fault tolerance. Disadvantage: Complexity, communication overhead.
  • Mobile OS: Operating systems for smartphones and tablets. E.g., Android, iOS. Advantage: Touch interface, battery optimization, connectivity. Disadvantage: Limited hardware control, sandboxing.

Key Terms

  • Operating System, Resource Manager, Extended Machine, Batch OS, Time-Sharing OS, Real-Time OS, Distributed OS, Mobile OS, Process, Thread, Scheduler, Kernel, User Space, Kernel Space

Unit Summary

Operating systems evolve from simple batch processors to complex, resource-managing systems that provide user-friendly interfaces while efficiently utilizing hardware. The OS serves as both a resource manager, ensuring efficient and fair allocation of hardware components, and an extended machine, hiding hardware complexity from users. Understanding the different types of operating systems helps in selecting the appropriate system for specific applications, from real-time control systems to general-purpose computing and mobile devices.

Practice Questions

Q1. What are the two primary roles of an operating system? (Answer: Resource manager and extended machine.)

Q2. What is the difference between a batch OS and a time-sharing OS? (Answer: Batch OS processes jobs without user interaction in batches; time-sharing OS allows multiple users to interact simultaneously by time-sharing the CPU. Batch has no user interaction; time-sharing is interactive.)

Q3. List four types of operating systems and one example of each. (Answer: Batch (e.g., early payroll systems), Time-sharing (e.g., Unix), Real-time (e.g., VxWorks), Distributed (e.g., Linux clusters), Mobile (e.g., Android).)

Q4. What is the main advantage of a real-time operating system? (Answer: Strict timing constraints with guaranteed response time bounds, making it suitable for industrial control and safety-critical systems.)

Q5. Why is the OS called an "extended machine"? (Answer: It provides a convenient, efficient, and user-friendly interface to the underlying hardware, hiding complexity and making the computer easier to use.)


Unit 2: Operating System Structure

Teaching Hours: 2 (indicative)

Introduction: The operating system structure refers to the logical organization of operating system components. Different OS designs have different structural approaches, each with advantages and trade-offs.

Layered System: The OS is divided into layers, each built on top of lower layers. The bottom layer is the hardware, and the top layer is the user interface. Each layer relies only on the functions of the layer below it.

  • Advantages: Modular design simplifies debugging and system verification. Each layer has a well-defined interface. Debugging is easier because a bug is confined to one layer.
  • Disadvantages: Performance overhead due to multiple layer calls. inflexibility — adding new functionality may require redesigning layers. The original Unix XV3 OS had 7 layers, and adding new services was challenging.

Kernel: The core of the operating system that provides essential services. The kernel runs in kernel (privileged) mode and has direct access to hardware. It remains in memory at all times during system operation. Services include process management, memory management, I/O control, and inter-process communication.

Types of Kernel:

  • Monolithic/Macro Kernel: All OS services run in kernel mode. Advantage: High performance (no context switching between layers). Disadvantage: A bug in one service can crash the entire system. Examples: Traditional Unix, Linux (though Linux supports loadable modules).
  • Micro / Exo-Kernel: Only essential services (IPC, basic scheduling) run in kernel mode. Other services run in user mode as separate processes. Advantage: Increased stability (a bug in a non-essential service doesn't crash the kernel). Disadvantage: Performance overhead from inter-process communication. Examples: Minix, L4.
  • Modular Kernel: Similar to monolithic but supports loadable modules. Services can be added/removed at runtime without rebooting. Examples: Modern Linux, Windows.

Client-Server Model: The OS functions are split into client and server processes. Clients request services from servers via message passing. Examples: Print server, file system server, DNS server. Advantage: Flexibility, easier to update individual components. Disadvantage: Communication overhead, complexity in designing interfaces.

Virtual Machines: Software emulation of a complete computer system. Each VM runs its own OS and applications. Advantages: Isolation, testing different OS on same hardware, server consolidation. Examples: VMware, VirtualBox, KVM.

Shell: The command-line interpreter that provides an interface between the user and the kernel. The shell reads user commands and executes them by calling the kernel. Common shells: bash, csh, zsh in Unix; Command Prompt, PowerShell in Windows.

Key Terms

  • Layered System, Kernel, Monolithic Kernel, Micro Kernel, Exo-Kernel, Modular Kernel, Client-Server Model, Virtual Machine, Shell, Privileged Mode, User Mode, System Call

Unit Summary

The structure of an operating system determines how its components are organized and how they interact. Layered designs provide modularity and ease of debugging, while microkernels improve stability by moving services out of the kernel. Modern kernels often use a modular approach, combining the performance of monolithic kernels with the flexibility of modular design. The client-server model and virtual machines are important concepts for distributed systems and isolation, respectively. The shell provides the user interface for interacting with the kernel through commands.

Practice Questions

Q1. What is a layered operating system? (Answer: The OS is divided into layers, each built on top of lower layers, with the hardware at the bottom and the user interface at the top. Each layer relies only on the functions of the layer below it.)

Q2. What are the advantages and disadvantages of a monolithic kernel? (Answer: Advantage: High performance, no context switching between layers. Disadvantage: A bug in one service can crash the entire system. Example: Traditional Unix, Linux.)

Q3. What is the difference between a microkernel and a monolithic kernel? (Answer: Microkernel: only essential services in kernel mode, others in user mode; more stable but slower due to IPC overhead. Monolithic: all services in kernel mode; faster but less stable. A bug in a monolithic kernel crashes the whole system.)

Q4. What is a virtual machine? (Answer: Software emulation of a complete computer system that runs its own OS and applications. Used for isolation, testing, and server consolidation.)

Q5. What is the role of the shell in an operating system? (Answer: The shell is the command-line interpreter that provides an interface between the user and the kernel, reading commands and executing them through system calls.)


Unit 3: Process Management

Teaching Hours: 15 (indicative)

Process Concepts:

  • Definitions of Process: A process is an active entity representing a program in execution. It includes the program counter, stack, data section, and heap. A process is more than a program code; it's the instance of execution with its own state and resources.

  • The Process Model: The process model defines what a process is and how it behaves. The basic process model includes the program counter, stack pointer, memory address space, and OS resources (files, I/O devices).

  • Process States: A process can be in one of the following states:

    • New: Process is being created.
    • Ready: Process is waiting to be assigned to a processor.
    • Running: Instructions are being executed.
    • Waiting (or Blocked): Process is waiting for some event (I/O completion, signal).
    • Terminated: Process has finished execution.
  • Process State Transition: Process moves between states as execution progresses. Common transitions:

    • New → Ready: When a process is created and added to the ready queue.
    • Ready → Running: When the scheduler dispatches the process to the CPU.
    • Running → Ready: When the time quantum expires (preemption) or a higher-priority process becomes ready.
    • Running → Waiting: When the process requests I/O or awaits some event.
    • Waiting → Ready: When the I/O completes or the event occurs.
    • Running → Terminated: When the process finishes execution.
    • Any state → Terminated: When an error occurs or the process is killed.
  • The Process Control Block (PCB): The PCB is the OS data structure that contains all information about a process. PCB contents:

    • Process state (new, ready, running, waiting, terminated)
    • Program counter (next instruction to execute)
    • CPU registers (context for resumption)
    • CPU scheduling information (priority, scheduling queue pointer)
    • Memory management information (base and limit registers, page tables)
    • Accounting information (CPU time, time limits, account numbers)
    • I/O status information (list of open files, I/O devices allocated)
  • Operations on Processes:

    • Creation: Creating a new process. Mechanisms: fork() in Unix, CreateProcess() in Windows. A new process may inherit resources from the parent.
    • Termination: Ending a process. Mechanisms: exit(), kill(). The OS reclaims all process resources (memory, file descriptors, etc.).
    • Hierarchies: Parent-child relationships via process creation. The parent is the creator; the child inherits certain attributes. Termination of a parent may cause termination of children (orphan process adoption by init/reaper).
    • Implementation: Process creation involves allocating a PCB, assigning a unique process ID (PID), copying resources, and initializing the process state.

Inter-Process Communication and Synchronization:

  • Race Condition: Occurs when multiple processes access shared data and the outcome depends on the timing of their execution. The critical section is the code segment that accesses shared data, and only one process should execute in the critical section at a time.

  • Critical Regions: A section of code that accesses shared data or resources. Only one process should be in its critical region at any time to avoid race conditions.

  • Avoiding Critical Region:

    • Mutual Exclusion: Ensuring that no two processes are in their critical regions at the same time.
    • Critical Region Conditions:
      1. Mutual exclusion: Only one process in critical region at a time.
      2. Progress: If no process is in critical region, the decision of which process enters next cannot be made only by processes in that region.
      3. Bounded waiting: There exists a bound on how many times other processes are allowed to enter their critical regions after a process has requested entry.
  • Proposals for Achieving Mutual Exclusion:

    • Disabling Interrupts: Temporarily disable all interrupts during critical region execution. Simple but not applicable to multi-processor systems and degrades performance.
    • Lock Variable: Use a variable that is set when entering the critical region and cleared when leaving. Susceptible to the "test-and-test-and-set" problem.
    • Strict Alteration (Peterson's Solution): For two processes, uses two boolean flags and a turn variable to ensure mutual exclusion. Guarantees mutual exclusion and progress but does not scale to more than two processes.
    • The TSL Instruction: Test-and-Set Lock instruction atomically tests and sets a variable. Guarantees mutual exclusion on single-processor systems.
    • Sleep and Wakeup: Process sleeps if critical region is busy; woken up when the region becomes free. Requires a condition variable or similar mechanism.
  • Types of Mutual Exclusion:

    • Semaphore: A variable or abstract data type used to control access to shared resources. Types:
      • Binary Semaphore: Takes values 0 or 1; used as a lock.
      • Counting Semaphore: Takes non-negative integer values; used for resource counting (e.g., number of available instances of a resource).
    • Monitors: High-level synchronization construct that combines mutual exclusion with condition variables. Only one process can be active in a monitor at a time. Condition variables allow processes to wait for certain conditions.
    • Mutex: A locking mechanism that provides mutual exclusion. Similar to a binary semaphore but with ownership semantics (only the process that locked it can unlock it).
    • Message Passing: Processes communicate by sending messages to each other, avoiding shared memory entirely. Each process has its own memory space, and communication occurs via explicit messages.
    • Bounded Buffer: A fixed-size buffer that allows producers to add items and consumers to remove items, with synchronization to avoid overflow/underflow.
  • Classical IPC Problems:

    • Dining Philosophers Problem: Five philosophers sit around a table with five forks. Each philosopher needs two forks to eat. Problem: potential deadlock (all philosophers pick up left fork, none can pick up right) or starvation.
    • The Readers and Writers Problem: Multiple readers can read simultaneously, but writers have exclusive access. Variants: reader preference, writer preference, fair approach.
    • The Sleeping Barber's Problem: A barber sleeps when no customers are present. Customers enter, sit in the waiting room, and wake the barber when ready. If the waiting room is full, customers leave. Synchronization between barber sleep/wake and customer seating/haircut.

Thread Concepts:

  • Definitions of Threads: A thread is a lightweight process, the smallest unit of CPU utilization. It includes a thread ID, program counter, register set, and stack. Multiple threads within the same process share the same code section, data section, and OS resources (files, signals), but each has its own stack and program counter.

  • Types Of Thread:

    • User-Level Threads (ULT): Managed by a user-level library. Advantage: No kernel support needed, can run on any OS. Disadvantage: Kernel is unaware of threads; cannot take advantage of multiprocessing (if one thread blocks, the entire process blocks).
    • Kernel-Level Threads (KLT): Managed by the operating system kernel. Advantage: Kernel can schedule threads across multiple processors; if one thread blocks, the kernel can schedule another thread of the same process. Disadvantage: Overhead of kernel involvement in every thread operation.
  • Benefits of Multithreading:

    • Responsiveness: If one thread blocks, others continue (especially important in GUIs).
    • Resource sharing: Within the same process, threads share memory and resources.
    • Economy: Creating a thread is much cheaper than creating a new process.
    • Scalability: Kernel-level threads can take advantage of multiprocessor systems.
  • Multithreading Models:

    • Many-to-One Model: Many user-level threads map to one kernel-level thread. The kernel sees only one thread per process. Advantage: No kernel overhead for thread operations. Disadvantage: Cannot take advantage of multiprocessing; one thread blocks, the whole process blocks.
    • One-to-One Model: One user-level thread maps to one kernel-level thread. Advantage: Can take advantage of multiprocessing; if one thread blocks, others continue. Disadvantage: More kernel overhead; creating a thread requires kernel support.
    • Many-to-Many Model: Many user-level threads map to many kernel-level threads. The kernel schedules multiple threads from the same process. Advantage: Best of both worlds; can take advantage of multiprocessing and handles blocking well. Disadvantage: Complex implementation; example: Windows XP/7 threads, Solaris.

Process Scheduling:

  • Basic Concept: The CPU scheduler selects one of the processes in memory whose state is ready to execute, and allocates the CPU to that process. Scheduling decisions can be made when a process switches from running to waiting state, from running to ready state, from waiting to ready state, or from running to termination state.

  • Type of Scheduling:

    • Preemptive Scheduling: The CPU can be taken away from a running process before it finishes its time slice. Used in time-sharing systems. Examples: Round-Robin, Priority preemptive.
    • Nonpreemptive Scheduling: Once a process starts executing, it runs until it completes or switches to waiting state. Used in real-time systems. Examples: First-Come-First-Served (FCFS).
    • Batch Scheduling: Optimized for batch systems where the goal is throughput, not response time. Jobs are collected and processed in batches.
    • Interactive Scheduling: Optimized for interactive systems where the goal is good response time. Examples: Round-Robin, Shortest Remaining Time First.
    • Real-Time Scheduling: Optimized for real-time systems where the goal is to meet deadlines. Examples: Rate Monotonic Scheduling (RMS), Earliest Deadline First (EDF).
  • Scheduling Criteria or Performance Analysis:

    • CPU Utilization: Keep the CPU as busy as possible. Ideally 80-90% utilization.
    • Throughput: Number of processes completed per unit time. For batch systems, higher is better. For interactive systems, response time matters more.
    • Waiting Time: Total time a process spends in the ready queue. Average waiting time should be minimized.
    • Turnaround Time: Time from process submission to completion. Turnaround time = waiting time + burst time + I/O time.
    • Response Time: Time from request submission to first response. Critical for interactive systems.
  • Scheduling Algorithm:

    • First Come First Served (FCFS): Nonpreemptive; processes executed in arrival order. Advantage: Simple, fair. Disadvantage: Convoy effect short processes wait for long processes.
    • Shortest-Job-First (SJF): Can be preemptive (Shortest Remaining Time First) or nonpreemptive. Advantage: Minimizes average waiting time. Disadvantage: Requires knowing burst times in advance; may starve long processes.
    • Shortest Process Next (SPN): Nonpreemptive SJF.
    • Shortest Remaining Time Next (SRTN): Preemptive SJF.
    • Round-Robin (RR): Each process gets a small time quantum (e.g., 10-100 ms). Preemptive. Advantage: Good response time, time-sharing. Disadvantage: Performance depends on time quantum size; large quantum behaves like FCFS, small quantum increases context switching overhead.
    • Priority: Each process has a priority; the CPU is allocated to the highest-priority process. Can be preemptive or nonpreemptive. Advantage: Important processes get served first. Disadvantage: Starvation of low-priority processes; aging can mitigate.
    • Fair Share: CPU time allocated based on fair share of resources. Used in multi-user systems.
    • Guaranteed: Provides guaranteed CPU time to each process. Used in real-time and multimedia systems.
    • Lottery Scheduling: Processes have lottery tickets; the CPU is allocated based on random drawing. Advantage: probabilistic fairness, easy to implement priority. Disadvantage: stochastic nature, not suitable for hard real-time.
    • HRN (Highest Response Ratio Next): Priority = (waiting time + burst time) / burst time. Favors short jobs that have waited long, preventing starvation.
    • Multiple Queue: Multiple ready queues with different scheduling algorithms. Advantage: Can mix scheduling algorithms for different process types. Disadvantage: Complexity in deciding which queue to use.
    • Multilevel Feedback Queue: Processes can move between queues based on their behavior (CPU burst length, I/O pattern). Advantage: Adaptive, combines benefits of multiple algorithms. Disadvantage: Complex tuning required; parameters must be set empirically.
  • Some Numerical Examples on Scheduling:

    Worked Example: Given three processes P1, P2, P3 with burst times 10, 5, 8 and arrival times 0, 2, 4 using FCFS scheduling:

    Solution:

    • P1: Arrival 0, Burst 10. Runs from 0 to 10. Waiting time = 0.
    • P2: Arrival 2, Burst 5. Runs from 10 to 15. Waiting time = 10 - 2 = 8.
    • P3: Arrival 4, Burst 8. Runs from 15 to 23. Waiting time = 15 - 4 = 11.
    • Average waiting time = (0 + 8 + 11) / 3 = 19 / 3 = 6.33.

    Worked Example: Same processes using SJF (nonpreemptive):

    • At time 0, only P1 available. P1 runs from 0 to 10.
    • At time 10, both P2 (burst 5) and P3 (burst 8) are available. SJF selects P2 (shorter).
    • P2 runs from 10 to 15. P3 runs from 15 to 23.
    • Waiting time: P1 = 0, P2 = 10 - 2 = 8, P3 = 15 - 4 = 11. Average = 6.33 (same as FCFS in this case).

    Worked Example: Round-Robin with time quantum = 3:

    • Time 0-3: P1 runs (remaining 7). Ready queue: [P2, P1].
    • Time 3-6: P2 runs (remaining 2). Ready queue: [P1, P3, P2].
    • Time 6-9: P1 runs (remaining 4). Ready queue: [P3, P2, P1].
    • Time 9-12: P3 runs (remaining 5). Ready queue: [P2, P1, P3].
    • Time 12-14: P2 runs to completion (remaining 2 < 3). Finish time 14.
    • Time 14-17: P1 runs (remaining 1). Ready queue: [P3, P1].
    • Time 17-20: P3 runs (remaining 2). Ready queue: [P1, P3].
    • Time 20-21: P1 runs to completion (remaining 1 < 3). Finish time 21.
    • Time 21-23: P3 runs to completion (remaining 2 < 3). Finish time 23.
    • Completion times: P1 = 21, P2 = 14, P3 = 23.
    • Turnaround time: P1 = 21, P2 = 12, P3 = 19. Average = 52 / 3 ≈ 17.33.
    • Waiting time: P1 = 11, P2 = 7, P3 = 11. Average = 29 / 3 ≈ 9.67.

Key Terms

  • Process, Process Control Block (PCB), Process State, Process Transition, Race Condition, Critical Section, Inter-Process Communication, Synchronization, Thread, User-Level Thread, Kernel-Level Thread, Multithreading Model, Scheduling Algorithm, FCFS, SJF, Round-Robin, Priority, Preemptive, Nonpreemptive, Convoy Effect

Unit Summary

Process management is a core operating system function that deals with the creation, scheduling, and termination of processes. Understanding process states, the PCB, and state transitions is fundamental. Scheduling algorithms determine how the CPU is allocated among competing processes, and each algorithm has trade-offs between fairness, response time, and throughput. Inter-process communication and synchronization mechanisms are essential for cooperative processes sharing data. Threads provide a lighter-weight unit of execution within a process, enabling concurrency and improved performance on multiprocessor systems.

Practice Questions

Q1. What is a process? (Answer: An active entity representing a program in execution, including the program counter, stack, data section, and heap, along with OS resources.)

Q2. What are the five process states and their meanings? (Answer: New (being created), Ready (waiting for CPU), Running (executing), Waiting/Blocked (waiting for I/O or event), Terminated (finished execution).)

Q3. What is the Process Control Block (PCB)? (Answer: The OS data structure containing all information about a process: state, program counter, CPU registers, scheduling info, memory info, accounting info, I/O status.)

Q4. What is a race condition? (Answer: Occurs when multiple processes access shared data and the outcome depends on the timing of their execution. The critical section is the code segment accessing shared data.)

Q5. Differentiate between user-level threads and kernel-level threads. (Answer: User-level threads are managed by a user library; kernel-level threads are managed by the OS. ULT: no kernel support needed, but cannot use multiprocessing. KLT: kernel aware, can use multiprocessing, but has overhead.)

Q6. What are the benefits of multithreading? (Answer: Responsiveness (blocked thread doesn't halt others), resource sharing (threads within same process share memory), economy (cheaper than process creation), scalability (kernel threads use multiprocessors).)

Q7. Compare the many-to-one and many-to-many multithreading models. (Answer: Many-to-one maps many ULT to one KLT; cannot use multiprocessing. Many-to-many maps many ULT to many KLT; best of both worlds, can use multiprocessing and handles blocking well. Example: Solaris uses many-to-many.)

Q8. What is the convoy effect in FCFS scheduling? (Answer: Short processes wait extended times for long processes to complete, as the CPU executes processes in arrival order without preemption. The long process "convoyes" short processes behind it.)

Q9. Given processes with burst times 10, 5, 8 and arrival times 0, 2, 4 using FCFS, calculate average waiting time. (Answer: P1 waiting = 0, P2 waiting = 8, P3 waiting = 11, average = 6.33.)

Q10. What scheduling algorithm minimizes average waiting time, and what is its main disadvantage? (Answer: SJF minimizes average waiting time but requires knowing burst times in advance and may starve long processes.)


Unit 4: Deadlocks

Teaching Hours: 4 (indicative)

System Model:

  • System Resources: Resources used by processes can be preemptable or non-preemptable.

    • Preemptable Resources: Resources that can be taken away from a process (e.g., CPU, memory). Preemption may leave the process in an inconsistent state.
    • Non-Preemptable Resources: Resources that cannot be taken away while in use (e.g., printers, tape drives). Once allocated, the process must release voluntarily.
  • Conditions for Resource Deadlocks: Four necessary conditions for deadlock (Coffman conditions):

    1. Mutual Exclusion: At least one resource must be held in a non-shareable mode (only one process can use it at a time).
    2. Hold and Wait: A process must be holding at least one resource and waiting to acquire additional resources held by other processes.
    3. No Preemption: Resources cannot be forcibly taken from processes; they must be released voluntarily.
    4. Circular Wait: A closed chain of processes exists, where each process holds a resource needed by the next process in the chain.
  • Deadlock Modeling: Using a Resource Allocation Graph (RAG). Nodes: processes and resource types. Edges:

    • Assignment edge: from resource type to process (resource assigned to process).
    • Request edge: from process to resource type (process requesting resource).
    • A cycle in the RAG indicates deadlock if only one instance of each resource type exists.
  • The OSTRICH Algorithm: The ostrich algorithm "pretends that deadlocks never occur." It is the simplest deadlock strategy. The OS does nothing to prevent or detect deadlocks. Advantage: No overhead for deadlock handling. Disadvantage: If deadlock occurs, the system crashes or hangs, requiring restart. Used when deadlocks are rare and the cost of recovery is higher than the cost of ignoring them. Example: Some embedded systems, databases that use prevention instead.

Method of Handling Deadlocks:

  • Deadlock Prevention: Design the system so that at least one of the four Coffman conditions cannot hold.
    • Prevent Mutual Exclusion: Make shareable resources that were previously exclusive. Not possible for non-shareable resources like printers, read-only files.
    • Prevent Hold and Wait: Require processes to request all resources at once (statically) or release all resources before requesting new ones. Disadvantage: Low resource utilization, may cause unnecessary waiting.
    • Prevent No Preemption: Allow resources to be preempted. Forcibly take a resource from a process if it's requesting another resource that's not available. Disadvantage: May disrupt process execution, not suitable for non-preemptable resources.
    • Prevent Circular Wait: Impose a total ordering on resource types and require that processes request resources in increasing order. Advantage: Simple to implement. Disadvantage: May be inconvenient for programmers.

Deadlock Avoidance:

  • Deadlock Avoidance: The OS dynamically examines the state of the system to ensure that there can never be a circular wait. The system only allocates resources when it's safe to do so.

    • Banker's Algorithm: A deadlock avoidance algorithm that tests for safety before allocating resources. It is named after the banking analogy: a bank only gives a loan if the customer's future needs can be satisfied.
      • Safe State: A state where there exists a sequence of all processes such that each process can obtain its maximum resources, complete, and release them. The system is in a safe state if such a sequence exists.
      • Unsafe State: A state that may lead to deadlock, but not necessarily. The system may or may not deadlock depending on future resource requests.

    Worked Example (Banker's Algorithm): Consider a system with 10 tape drives and three processes A, B, C with the following claims and current allocations:

    • Process A: Claim = 6, Allocation = 2, Need = 4
    • Process B: Claim = 5, Allocation = 1, Need = 4
    • Process C: Claim = 4, Allocation = 1, Need = 3
    • Total system resources = 10, Available = 10 - (2+1+1) = 6

    Safety Algorithm:

    1. Check if Need ≤ Available for any process. A needs 4 ≤ 6 ✓, B needs 4 ≤ 6 ✓, C needs 3 ≤ 6 ✓.
    2. Find process whose need ≤ available, e.g., C. Execute C (it will complete and release its allocation of 1). New available = 6 + 1 = 7.
    3. Check again. A needs 4 ≤ 7 ✓, B needs 4 ≤ 7 ✓. Execute B. New available = 7 + 1 = 8.
    4. Execute A. New available = 8 + 2 = 10.
    5. All processes can complete → system is in a safe state.

    Conclusion: The current allocation is safe. If A requests 2 more, B requests 2 more, the system can still satisfy both and remain safe.

Deadlock Detection:

  • Deadlock Detection: Periodically examine the system state to determine if a deadlock has occurred.

    • Single Instance of Each Resource Type: Use Resource Allocation Graph and check for cycles.
    • Multiple Instances of Each Resource Type: Use the Extended Resource Allocation Graph or Banker's Algorithm variant for detection.
    • Detection Algorithm: Periodically run an algorithm that checks all processes and resources to find deadlocked processes.
  • Recovery from Deadlock:

    • Process Termination: Abort one or more deadlocked processes. Two approaches:
      • Abort all deadlocked processes.
      • Abort processes one by one until the deadlock is resolved. Consider which process to terminate: priority, estimated running time, resources currently held.
    • Resource Preemption: Take resources from some processes and give them to others. Two approaches:
      • Preempt resources from one process and give to another.
      • Roll back the preempted process to a safe state and restart it.

Key Terms

  • Deadlock, System Resource, Preemptable, Non-Preemptable, Coffman Conditions, Mutual Exclusion, Hold and Wait, No Preemption, Circular Wait, Resource Allocation Graph, OSTRICH Algorithm, Deadlock Prevention, Deadlock Avoidance, Banker's Algorithm, Safe State, Unsafe State, Detection, Recovery

Unit Summary

Deadlocks occur when four necessary conditions (mutual exclusion, hold and wait, no preemption, circular wait) simultaneously hold. Prevention ensures one condition cannot occur, while avoidance (e.g., Banker's Algorithm) dynamically checks for safe states. Detection periodically examines the system to find deadlocked processes, and recovery involves either process termination or resource preemption. Understanding deadlock handling is essential for building reliable concurrent systems.

Practice Questions

Q1. What are the four Coffman conditions necessary for deadlock? (Answer: Mutual Exclusion, Hold and Wait, No Preemption, Circular Wait. All four must hold for deadlock to occur.)

Q2. Which of the four Coffman conditions is most difficult to prevent, and why? (Answer: No Preemption is difficult because many resources (printers, tape drives) cannot be preempted without causing inconsistency. Taking away a printer mid-print job ruins the printout.)

Q3. What is the Banker's Algorithm and what problem does it solve? (Answer: The Banker's Algorithm is a deadlock avoidance algorithm that tests for safety before allocating resources. It ensures the system remains in a safe state where all processes can complete. It is named after the banking analogy where a bank only loans money if the customer's future needs can be satisfied.)

Q4. What is a safe state in the Banker's Algorithm? (Answer: A state where there exists a sequence (called a safe sequence) of all processes such that each process can obtain its maximum resources, complete, and release them. The system is not in deadlock, and no deadlock will occur if processes request resources responsibly.)

Q5. What is the OSTRICH Algorithm? (Answer: A deadlock strategy that does nothing; the OS pretends deadlocks never occur. Used when deadlocks are rare and recovery cost exceeds ignoring cost.)

Q6. How can deadlock be recovered from? (Answer: Process termination (abort one or more processes) or resource preemption (take resources from one process and give to another). Termination may kill desired processes; preemption may disrupt the process.)

Q7. In a resource allocation graph with one instance of each resource type, a cycle indicates... (Answer: deadlock. The cycle represents a circular wait condition where each process holds a resource needed by the next.)


Unit 5: Memory Management

Teaching Hours: 7 (indicative)

Basic Memory Management:

  • Memory Hierarchy: The organized levels of memory storage from fastest/smallest to slowest/largest: Registers → Cache (L1, L2, L3) → Main Memory (RAM) → Secondary Storage (Disk, SSD). The memory hierarchy provides a trade-off between speed, cost, and capacity.

  • Logical Versus Physical Address Space:

    • Logical Address: Generated by the CPU; also called virtual address. The process sees this address space.
    • Physical Address: The actual memory location in RAM. The mapping from logical to physical is done by the MMU (Memory Management Unit).
    • Address Translation: The MMU translates logical addresses to physical addresses using page tables or segment tables.
  • Memory Management with Bitmaps and with Linked List:

    • Bitmap: A bit map where each bit represents a block of memory. Bit = 1 means allocated, Bit = 0 means free. Advantage: Easy to find free blocks. Disadvantage: Large memory overhead for the bitmap itself for large memories.
    • Linked List: Free memory blocks are linked together using a linked list. Advantage: Dynamic, no fixed-size overhead. Disadvantage: Requires traversal to find free blocks.
  • Memory Management without Swapping: All processes reside in main memory while executing. No swapping to disk. Advantage: Simpler, faster access. Disadvantage: Limited degree of multiprogramming.

  • Contiguous Memory Allocation: Each process occupies a contiguous block of memory.

    • Memory Protection: Base and limit registers protect memory. The base register specifies the smallest legal physical address; the limit register specifies the range. A logical address must be less than the limit to be mapped to a physical address.
    • Memory Allocation: Techniques for allocating memory blocks to processes.
    • Fragmentation: Wasted memory space.
      • Internal Fragmentation: Allocated memory may be slightly larger than requested. The OS allocates a fixed-size partition, and the process uses only part of it. Example: allocating 65 KB in a 100 KB partition leaves 35 KB internal fragmentation.
      • External Fragmentation: Total memory space is enough to satisfy a request, but it is not contiguous. Example: 100 KB total free memory broken into 3 × 30 KB partitions; a 70 KB request cannot be satisfied. Compaction (shuffling memory contents) can reduce external fragmentation.
    • Fixed Partitioning Vs. Variable Partitioning:
      • Fixed Partitioning: Memory divided into fixed-size partitions at system boot. Each partition holds exactly one process. Advantage: Simple. Disadvantage: Internal fragmentation, inflexible partition sizes.
      • Variable Partitioning: Partitions created dynamically to fit the process size. Advantage: No internal fragmentation. Disadvantage: External fragmentation, more complex allocation.
  • Relocation and Protection: Relocation moves processes between memory partitions. Base register provides relocation. Protection ensured by base and limit registers.

  • Coalescing and Compaction:

    • Coalescing: Combining adjacent free partitions into a larger free partition. Reduces external fragmentation.
    • Compaction: Moving memory contents to collect all free space into one large block. Expensive operation; requires moving all processes.

Virtual Memory:

  • Background: Virtual memory separates the user logical memory from physical memory. It allows the execution of processes that are not completely in memory. This increases the degree of multiprogramming.

  • Paging: Physical memory is divided into fixed-size blocks called frames, and logical memory is divided into blocks of the same size called pages. Advantage: No external fragmentation (pages are fixed size). Disadvantage: Internal fragmentation (last page may not be fully used).

    • Structure of Page Table: Maps page numbers to frame numbers.
      • Hierarchical Page Table: Multi-level page table to reduce memory overhead. Two-level: page directory + page table. Three-level for large address spaces.
      • Hashed Page Table: Uses a hash table to speed up page table lookup. Effective for large address spaces.
      • Inverted Page Table: One entry per physical frame, containing the process ID and page number. Reduces memory overhead for large memories. Example: PowerPC, SPARC.
    • Shared Page Table: Multiple processes sharing the same physical page. Used for shared memory and shared libraries.
  • Demand Paging: Pages are loaded into memory only when needed (on demand). Advantage: Less I/O needed to start a process, more programs can fit in memory. Disadvantage: Page fault overhead when accessing a page not in memory.

  • Page Replacement Algorithms: When a page fault occurs and memory is full, an existing page must be replaced. Algorithms:

    • FIFO (First-In-First-Out): Replace the page that has been in memory the longest.
    • Optimal (OPT): Replace the page that will not be used for the longest time in the future. Impossible to implement in practice (requires future knowledge), but used for performance comparison.
    • LRU (Least Recently Used): Replace the page that has not been used for the longest time. Approximation of OPT. Performs well but requires hardware support (timestamp bits, counters).
    • SCP (Second-Chance Page also known as Clock Algorithm): gives a "second chance" to pages with the reference bit set. Uses a circular list and reference/usage bits.
    • NRU (Not Recently Used): Each page has a reference bit and a modify bit. Pages are classified: (0,0) not used, modified; (0,1) not used, unmodified; (1,0) used, modified; (1,1) used, unmodified. Select from the lowest class.

    Worked Example (FIFO): Given reference string: 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5 with 3 frames.

    • 1: load 1 → frames: [1, -, -]
    • 2: load 2 → frames: [1, 2, -]
    • 3: load 3 → frames: [1, 2, 3]
    • 4: page fault, replace 1 (FIFO) → frames: [4, 2, 3]
    • 1: page fault, replace 2 → frames: [4, 1, 3]
    • 2: page fault, replace 3 → frames: [4, 1, 2]
    • 5: page fault, replace 4 → frames: [5, 1, 2]
    • 1: hit (1 is in frames)
    • 2: hit (2 is in frames)
    • 3: page fault, replace 5 → frames: [3, 1, 2]
    • 4: page fault, replace 1 → frames: [3, 4, 2]
    • 5: page fault, replace 2 → frames: [3, 4, 5]
    • Total page faults = 9.

    Worked Example (LRU): Same reference string with 3 frames.

    Step Reference Frame 1 Frame 2 Frame 3 Page Fault? LRU Order (newest → oldest)
    1 1 1 - - Yes 1
    2 2 2 1 - Yes 2, 1
    3 3 3 2 1 Yes 3, 2, 1
    4 4 4 3 2 Yes 4, 3, 2
    5 1 1 4 3 Yes 1, 4, 3
    6 2 2 1 4 Yes 2, 1, 4
    7 5 5 2 1 Yes 5, 2, 1
    8 1 1 5 2 Hit 1, 5, 2
    9 2 2 1 5 Hit 2, 1, 5
    10 3 3 2 1 Yes 3, 2, 1
    11 4 4 3 2 Yes 4, 3, 2
    12 5 5 4 3 Yes 5, 4, 3

    Swipe to see all columns

    Total page faults = 10 (hits on references 8 and 9).

    LRU replaces the page that has not been used for the longest time (the oldest entry in the LRU order). On a hit, the referenced page moves to the newest position; on a fault, the new page loads as newest and the oldest page is evicted when frames are full.

  • Thrashing: Occurs when the processor spends most of its time paging instead of executing. Causes: too many processes in memory, insufficient physical memory. Solution: working set model, reduce the number of processes, add more memory.

  • Segmentation: Memory management scheme that supports user view of memory. Memory is divided into variable-sized segments (code, data, stack, heap). Each segment has a base and limit. Segmentation combined with paging (segmented paging) provides the benefits of both.

  • Segmentation With Paging: Combines segmentation (user-friendly view) with paging (no external fragmentation). Segments are divided into pages, and each page is mapped to a frame. Example: Intel x86 segmented paging model.

Key Terms

  • Memory Management, Paging, Virtual Memory, Page Table, Frame, Page, Demand Paging, Page Replacement, FIFO, LRU, OPT, Thrashing, Segmentation, Logical Address, Physical Address, MMU, Memory Hierarchy, Fragmentation, Internal Fragmentation, External Fragmentation, Compaction, Coalescing

Unit Summary

Memory management is a critical operating system function that allocates main memory to processes. Paging eliminates external fragmentation by using fixed-size blocks, while virtual memory extends the apparent memory capacity using disk space. Page replacement algorithms determine which pages to evict when memory is full, balancing implementation cost and performance. Thrashing indicates a need for more memory or fewer processes. Segmentation provides a user-friendly view of memory divided into logical units. Modern systems often use paged segmentation, combining the benefits of both approaches.

Practice Questions

Q1. What is the difference between internal and external fragmentation? (Answer: Internal fragmentation occurs when allocated memory is slightly larger than requested (wasted space within allocated block). External fragmentation occurs when total free memory is enough but not contiguous (wasted space between allocated blocks).)

Q2. What is the purpose of virtual memory? (Answer: Virtual memory separates user logical memory from physical memory, allowing execution of processes not completely in memory and increasing the degree of multiprogramming.)

Q3. Compare FIFO and LRU page replacement algorithms. (Answer: FIFO replaces the page that entered memory first; simple but performs poorly. LRU replaces the page not used for the longest time; approximates OPT, performs well, but requires hardware support for timestamp tracking.)

Q4. What is thrashing? (Answer: Thrashing occurs when the processor spends most of its time paging instead of executing, caused by too many processes in memory or insufficient physical memory. Leads to severe performance degradation.)

Q5. In a system with FIFO page replacement and 3 frames, reference string: 1, 2, 3, 4, 1, 2. How many page faults occur? (Answer: 6 page faults. Frame trace: 1 → [1,-,-], 2 → [1,2,-], 3 → [1,2,3], 4 → replace 1 → [4,2,3], 1 → replace 2 → [4,1,3], 2 → replace 3 → [4,1,2].)

Q6. What is the difference between hierarchical and inverted page tables? (Answer: Hierarchical page tables use multiple levels (page directory + page table) to reduce memory overhead for large address spaces. Inverted page tables have one entry per physical frame containing the process ID and page number, reducing overhead for large memories. Example: PowerPC, SPARC.)

Q7. Explain the concept of the reference bit in the Clock page replacement algorithm. (Answer: Each page has a reference bit set by hardware when the page is accessed. The algorithm gives pages a "second chance" if the bit is 1, clearing the bit and moving forward. If the bit is 0, the page is replaced since it hasn't been recently used.)


Unit 6: Input/Output Device Management

Teaching Hours: 4 (indicative)

Principle of I/O Devices:

  • Device Controllers: Each I/O device has a controller that controls the device and serves as an interface to the CPU. The controller translates commands from the CPU into device-specific operations. Multiple devices can share a single controller.

  • Memory Mapped I/O: I/O devices are mapped into the system's memory address space. The same address bus is used for memory and I/O. Instructions that read/write memory addresses also read/write I/O registers. Advantage: Simple to program, uses standard memory instructions. Disadvantage: Reduces the amount of address space available for memory.

  • Direct Memory Access (DMA): Allows I/O devices to transfer data to/from memory without CPU involvement for each byte/word. The CPU initializes the DMA transfer, then the DMA controller handles the transfer directly. When transfer is complete, the DMA controller generates an interrupt.

    • DMA Transfer Process:
      1. CPU loads DMA controller with source address, destination address, and transfer count.
      2. CPU goes about other business (interrupt-driven or other tasks).
      3. DMA controller transfers data between device and memory directly.
      4. DMA controller generates an interrupt when transfer is complete.

Principle of I/O Software:

  • Goals of I/O Software: Device independence, device abstraction, error handling, and efficiency.
  • Program I/O: The CPU reads/writes I/O ports directly. The CPU waits for the device to complete each operation (synchronous). Advantage: Simple, suitable for slow devices. Disadvantage: CPU is idle waiting for slow device; inefficient.
  • Interrupt-Driven I/O: The CPU sends a command to the device and continues execution. When the device completes, it sends an interrupt to the CPU. The CPU then handles the interrupt. Advantage: CPU not idle waiting for device; improves efficiency.
  • I/O Using DMA: As described above, DMA transfers data without CPU intervention for each operation. The CPU is involved only at the start and end of the transfer.

I/O Software Layers:

  1. Interrupts Handler: Handles interrupt requests from devices. The ISR (Interrupt Service Routine) saves context, services the device, and restores context.
  2. Device Drivers: Software that controls specific devices. Translates generic I/O requests to device-specific commands. Each device has its own driver.
  3. Device Independent I/O Software: Provides a uniform interface to the rest of the OS. Hides device-specific details. Examples: file system, standard I/O package.
  4. User-Space I/O Software: Applications make system calls to perform I/O. The system call is trapped to the kernel, which invokes the appropriate device driver.

Disk Hardware:

  • Disk Structure: Platter(s), tracks, sectors, cylinder. Data stored as magnetic patterns on platters. Each platter has two surfaces, each surface has tracks, each track has sectors. A sector is the smallest addressable unit (typically 512 bytes or 4KB).
  • Disk Arm: Moves the read/write head to the desired track. Seek time is the time to move the arm.
  • Rotational Latency: The time waiting for the desired sector to rotate under the read/write head. Depends on RPM (rotations per minute).
  • Transfer Time: The time to read/write the data once the head is positioned. Depends on data density and transfer rate.

Disk Scheduling:

  • Seek Time: The time required for the disk arm to move to the requested track.

  • Rotational Delay (Latency): The time waiting for the desired sector to rotate under the head.

  • Transfer Time: The time to read/write the data.

  • Disk Scheduling Algorithms:

    • FCFS (First-Come First-Served): Serves requests in the order they arrive. Advantage: Fair, simple. Disadvantage: May cause long average seek time; no optimization.
    • SSTF (Shortest Seek Time First): Serves the request with the minimum seek time from the current head position. Advantage: Shorter average seek time than FCFS. Disadvantage: Starvation of requests far from the current position.
    • SCAN (Elevator): The disk arm moves in one direction, servicing requests until it reaches the end, then reverses direction. Advantage: Fairer than SSTF, bounded wait time. Disadvantage: May have longer wait times for some requests.
    • C-SCAN (Circular SCAN): Similar to SCAN, but the arm only moves in one direction (e.g., from track 0 to the highest track). When it reaches the end, it immediately returns to the beginning without servicing. Provides more uniform wait time.
    • LOOK: A variant of SCAN that moves only as far as the last request in each direction, rather than to the physical end. Shorter seek times than SCAN.
    • C-LOOK: A variant of C-SCAN that moves only as far as the last request in each direction, then immediately returns to the first request.

    Worked Example (FCFS): Current head position at track 50; requests: 20, 55, 80, 30, 70.

    • Service order: 50 → 20 → 55 → 80 → 30 → 70.
    • Seek distances: |50-20| = 30, |20-55| = 35, |55-80| = 25, |80-30| = 50, |30-70| = 40.
    • Total seek = 30 + 35 + 25 + 50 + 40 = 180. Average seek = 180 / 5 = 36.

    Worked Example (SSTF): Same requests, start at track 50.

    • 50 → 55 (seek 5, nearest unserviced). From 55 → 70 (seek 15). From 70 → 80 (seek 10). From 80 → 30 (seek 50). From 30 → 20 (seek 10).
    • Service order: 55, 70, 80, 30, 20.
    • Total seek = 5 + 15 + 10 + 50 + 10 = 90. Average seek = 90 / 5 = 18.

Key Terms

  • I/O Device, Device Controller, Memory Mapped I/O, DMA, Interrupt, Device Driver, Interrupt Service Routine, Disk Scheduling, FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK, Seek Time, Rotational Latency, Transfer Time

Unit Summary

I/O device management involves coordinating communication between the CPU and peripheral devices. Techniques range from program I/O (CPU waits for device) to interrupt-driven I/O and DMA (CPU continues other work). Disk scheduling algorithms optimize the order of disk requests to minimize seek time and rotational latency. Understanding these concepts is essential for building efficient systems that handle input/output effectively, particularly in performance-critical applications like databases and real-time systems.

Practice Questions

Q1. What is the difference between program I/O and DMA? (Answer: In program I/O, the CPU reads/writes each byte/word and waits for the device. In DMA, the DMA controller transfers data between device and memory without CPU involvement for each operation, reducing CPU overhead.)

Q2. What are the three components of disk access time? (Answer: Seek time (arm movement), rotational latency (waiting for sector to rotate under head), transfer time (reading/writing the data).)

Q3. Compare FCFS and SSTF disk scheduling algorithms. (Answer: FCFS serves requests in arrival order; simple but may cause long average seek time. SSTF serves the nearest request first; shorter average seek time but may starve requests far from the current position.)

Q4. Describe the SCAN (Elevator) disk scheduling algorithm. (Answer: The disk arm moves in one direction, servicing requests until it reaches the end of the disk, then reverses direction like an elevator. Provides fairer service than SSTF with bounded wait time.)

Q5. In C-SCAN, the disk arm moves from track 0 to the highest track, servicing requests, then instantly returns to track 0 without servicing. This provides... (Answer: more uniform wait time for all requests compared to SCAN, since each request is serviced approximately the same number of revolutions after the previous one.)


Unit 7: File System Interface Management

Teaching Hours: 2 (indicative)

File Concept:

  • File Naming: Rules and conventions for naming files. Typical rules: filename extension (e.g., .txt, .exe), case sensitivity (Unix case-sensitive, Windows case-insensitive), maximum length (e.g., 255 characters), prohibited characters (/, *, ?, etc.).

  • File Type: Classification of files based on content and format. Common types:

    • Text files: Sequences of characters, human-readable.
    • Binary files: Sequences of bytes, not necessarily human-readable (executables, images, databases).
    • Source files: Program source code.
    • Object files: Compiled, linkable object code.
    • Archive files: Collections of other files (e.g., .zip, .tar).
    • Device files: Represent hardware devices (e.g., /dev/sda in Unix).
  • File Attributes: Metadata about the file, maintained by the file system. Typical attributes:

    • Name: The file's name.
    • Identifier: Unique file ID (inode number in Unix).
    • Protection: Access rights (read, write, execute) for owner, group, others.
    • Size: File size in bytes.
    • Time-stamps: Creation time, modification time, access time.
    • Location: Pointer to the file's storage location on disk.
    • Owner: User who owns the file.
    • File type: Identifier of file format.
  • File Operations: Operations that can be performed on files.

    • Create: Create a new file.
    • Write: Write data to a file.
    • Read: Read data from a file.
    • Reopen: Reopen an already open file.
    • Truncate: Reduce file size to zero or specified size.
    • Delete: Remove a file from the file system.
    • Open/Close: Open a file for access, close when done.
  • File Types (detailed):

    • Sequence Files: Records stored sequentially. Records accessed sequentially or by key. Example: text files, data files.
    • Random Files (Relative Files): Records accessed directly by record number. Requires fixed-length records. Example: indexed sequential files.

File Access Methods:

  • Sequential Access: Records are accessed in sequence, one after another. The file is like a magnetic tape. Accessing a specific record requires scanning through all preceding records.
    • Suitable for: Batch processing, data where access pattern is sequential. Example: log files, payroll processing.
    • Direct Access (Random Access): Records are accessed directly by their location (address or record number) without scanning preceding records. The file is like a disk, where any record can be accessed in roughly the same time.
      • Keyed Access: Access by a key field (e.g., student ID, employee number). An index maps keys to disk locations.
    • Indexed Access: Uses an index structure to locate records quickly. The index contains (key, address) pairs.

File Access Methods (detailed):

  • Sequential Access Methods:

    • End-of-File: Read until end of file is reached.
    • Forward-Backward: Move forward and backward through the file.
    • Example: fgets() in C for sequential reading, tellg()/seekg() in C++ for position tracking.
  • Direct Access Methods:

    • Fixed-Length Records: Each record occupies the same number of bytes. The record position determines the address: address = base_address + (record_number × record_size).
    • Variable-Length Records: Records have different sizes. Indexing required to locate records. Techniques:
      • Indexing: Separate index structure maps keys to disk addresses.
      • Multilevel Indexing: B-tree or B+-tree index structures for efficient lookup.
      • Hashed Indexing: Hash function maps keys to disk addresses.

File Organization and Access:

  • Single-Level Directory System: One directory for all files. Simple, suitable for single-user, single-task systems. Drawback: No protection, all files in one namespace, difficult to manage as number of files grows.

  • Hierarchical Directory Systems: Directory tree structure. Advantages:

    • Grouping files into directories/subdirectories.
    • Same file name can exist in different directories.
    • Tree structure with root directory at the top.
    • Path names: Absolute path (from root) and relative path (from current directory).
    • Directory operations: Create, delete, rename directories.
  • Path Names:

    • Absolute Path: Full path from the root directory to the file. Example: /home/user/documents/report.txt.
    • Relative Path: Path relative to the current working directory. Example: documents/report.txt when CWD is /home/user.
  • Directory Operation:

    • Create Directory: mkdir in Unix, os.mkdir() in Python.
    • Delete Directory: rmdir in Unix (only empty directories), shutil.rmtree() in Python.
    • Rename Directory/File: rename in Unix, os.rename() in Python.

Access Methods:

  • Sequential: Access records in order. Example: reading a text file line by line.
  • Direct: Access any record by address. Example: reading record 5 from a disk file without reading records 1-4.
  • Indexed: Uses an index structure. Example: database indexed lookup, file system with inode index.

Protection:

  • Types of Access Control List:

    • Discretionary Access Control (DAC): Owner of the file determines access rights. Example: Unix file permissions (rwx for owner, group, others).
    • Access Control Matrix: Table where rows are subjects (users, processes) and columns are objects (files, devices), and entries specify access rights. More general and flexible than DAC.
  • Access Control Matrix: The conceptual model for protection. Rows: subjects (users, processes). Columns: objects (files, devices, printers). Entries: access rights (read, write, execute, append, delete, modify). The system checks the matrix when a process attempts an operation on an object to determine if the access is allowed.

Key Terms

  • File, File Naming, File Type, File Attributes, File Operations, Sequential Access, Direct Access, Indexed Access, Single-Level Directory, Hierarchical Directory, Absolute Path, Relative Path, Access Control List, DAC, Access Control Matrix, Inode

Unit Summary

The file system provides a structured way to store, organize, and access data on storage devices. File access methods (sequential, direct, indexed) determine how efficiently data can be retrieved. Protection mechanisms (ACLs, access control matrix) ensure that only authorized users and processes can access files. Hierarchical directory systems provide organization and naming flexibility, while access control protects data integrity. Understanding file system organization is essential for developing applications that read/write data reliably and securely.

Practice Questions

Q1. What is the difference between sequential access and direct access? (Answer: Sequential access reads records in order, one after another (like magnetic tape). Direct access reads any record directly by its address/location (like a disk) without reading preceding records.)

Q2. What is an absolute path? (Answer: Full path from the root directory to the file. Example: /home/user/documents/report.txt.)

Q3. What is the purpose of an access control list (ACL)? (Answer: To specify which users or processes are granted access to a file, and what operations they can perform (read, write, execute). DAC uses ACLs where the owner determines access.)

Q4. Describe the difference between a single-level directory system and a hierarchical directory system. (Answer: Single-level: one directory for all files, simple but no protection or organization. Hierarchical: tree-structured directories, allows grouping, same names in different directories, absolute/relative paths.)

Q5. Explain how direct access to a file record works with fixed-length records. (Answer: The byte address of record n is: base_address + (n × record_size). The OS uses the record number to calculate the exact disk location, enabling random access without scanning preceding records.)


Unit 8: Security Management

Teaching Hours: 3 (indicative)

Introduction: Operating system security involves protecting the system from unauthorized access, ensuring data integrity, and maintaining availability of services. Security is a fundamental requirement for modern computing systems, especially those connected to networks.

Security Problems:

  • Unauthorized Access: Users gaining access to system resources they shouldn't have. Examples: password guessing, exploiting vulnerabilities, social engineering.
  • Data Integrity: Unauthorized modification of data. Examples: hackers altering data, accidental corruption, software bugs.
  • Data Confidentiality: Unauthorized disclosure of sensitive information. Examples: eavesdropping, data theft, espionage.
  • Availability: Denial of service preventing legitimate users from accessing the system. Examples: DDoS attacks, malware flooding resources.

User Authentication:

  • Passwords: The most common authentication mechanism. Users provide a secret password verified against the stored password file.

    • Password Vulnerabilities: Short passwords, dictionary words, personal information (birth dates, names), reuse across systems, shoulder surfing.
    • Encrypted Password: Passwords stored encrypted (hashed) rather than in plain text. One-way hash functions (e.g., MD5, SHA-256) convert passwords to fixed-size hash values. The system hashes the entered password and compares the hash to the stored hash. No reversible decryption; only comparison.
    • One Time Password (OTP): Password valid for only one login session or transaction. Examples: TOTP (Time-based OTP), SOTP (Sequence-based OTP), hardware tokens (RSA SecurID). Prevents replay attacks.
    • Biometrics: Authentication using physical characteristics. Examples: fingerprint recognition, iris scan, facial recognition, voice print. Advantage: Hard to forge. Disadvantage: Expensive, privacy concerns, false acceptance/rejection rates.
  • User Authorization: Once authenticated, the OS determines what resources the user can access. Mechanisms:

    • File permissions: Read, write, execute access control.
    • Privilege levels: Superuser (root/administrator) vs. regular users.
    • Role-based access control (RBAC): Access based on assigned roles rather than individual user IDs. Role has permissions; users have roles.

Program Threats:

  • Trojan Horse: Malicious program disguised as legitimate software. Users willingly run it, but it performs harmful activities (data theft, backdoor creation). Trojan horses do not replicate themselves. Example: A game that appears legitimate but sends passwords to an external server.
  • Trap Door (Backdoor): A secret, undocumented entry point into a program that bypasses normal security checks. Example: A login backdoor that accepts a special password known only to the developer.
  • Stack and Buffer Overflow: Writing more data to a buffer than it can hold, overwriting adjacent memory including the return address on the stack. Can be exploited to redirect program execution to malicious code. Buffer overflow attacks overwrite the return address to point to injected shellcode.
  • Viruses: Self-replicating malware that attaches to legitimate programs. Requires user action to spread (running the infected program). Types: file viruses, boot sector macros, polymorphic viruses (change code to avoid detection).
  • Worms: Self-replicating malware that spreads automatically across networks without user action. Exploits network vulnerabilities. Example: Morris Worm (1988), WannaCry (2017). Worms consume bandwidth and can cause denial of service.
  • Denial of Services (DoS): Attempts to make a system resource unavailable to legitimate users. Types: flooding the network with packets, exploiting vulnerabilities to crash services, distributed DoS (DDoS) using multiple compromised systems.

System Threats:

  • Summary of threats: Viruses, worms, Trojan horses, DoS attacks, unauthorized access, data breaches. Defense in depth: multiple layers of security (physical, software, network, user awareness).

Key Terms

  • Operating System Security, Authentication, Authorization, Password, Encrypted Password, One-Time Password, Biometrics, Trojan Horse, Trap Door, Buffer Overflow, Virus, Worm, Denial of Service, DoS, Distributed DoS, DDoS, Access Control, RBAC

Unit Summary

Operating system security involves protecting the system from a wide range of threats including unauthorized access, malware, and denial of service attacks. Authentication (passwords, biometrics, OTP) verifies user identity, while authorization determines resource access. Program threats (Trojan horses, buffer overflows, viruses, worms) exploit program vulnerabilities, and system threats encompass the broader security landscape. Defense in depth, combining multiple security layers, is the recommended approach for robust OS security.

Practice Questions

Q1. What is the main difference between a virus and a worm? (Answer: A virus requires user action to spread (running an infected program), while a worm spreads automatically across networks without user action, exploiting vulnerabilities.)

Q2. How are encrypted (hashed) passwords different from plaintext passwords? (Answer: Encrypted passwords use a one-way hash function; the system stores the hash, not the actual password. When a user logs in, the system hashes the entered password and compares the hash to the stored hash. Plaintext passwords are stored as-is, making them vulnerable if the password file is compromised.)

Q3. What is a buffer overflow and how can it be exploited? (Answer: A buffer overflow occurs when more data is written to a buffer than it can hold, overwriting adjacent memory including the return address on the stack. Exploits redirect program execution to malicious code by overwriting the return address.)

Q4. What is RBAC and how does it differ from DAC? (Answer: RBAC (Role-Based Access Control) grants access based on assigned roles rather than individual user IDs. DAC (Discretionary Access Control) allows the file owner to determine access rights. RBAC is more scalable and administratively friendly for large organizations; DAC is more flexible for individual file sharing.)

Q5. What is a trap door (backdoor)? (Answer: A secret, undocumented entry point into a program that bypasses normal security checks. Can be intentionally placed by developers for debugging or maliciously for unauthorized access.)


Unit 9: Distributed Operating System

Teaching Hours: 4 (indicative)

Introduction: A distributed operating system runs on multiple independent processors (not necessarily the same hardware) where each processor has its own local memory. The processors communicate through various communication networks. The goal is to make the distributed system appear and be used as a single centralized computer.

Advantages of Distributed System over Centralized System:

  • Resource Sharing: Users can access remote devices, data, and information as if they were local. Printers, scanners, large storage, powerful CPUs can be shared across the network.
  • Computation Speed-Up: Large computations can be divided among multiple processors, reducing execution time. Parallel processing improves performance for suitable algorithms.
  • Reliability: If one processor fails, others can continue operating. No single point of failure. Graceful degradation rather than total system failure.
  • Scalability: Additional processors can be added to the system to increase capacity. Linear (or near-linear) scaling for many applications.
  • Communication: Processors communicate via various networks (LAN, WAN, Internet). Message passing, distributed shared memory.

Disadvantages of Distributed System over Independent PCs:

  • Complexity: Design and implementation of distributed systems are significantly more complex than standalone systems. Communication, coordination, and consistency are challenging.
  • Overhead: Communication between processors introduces latency and bandwidth overhead not present in standalone systems. Message passing requires serialization/deserialization.
  • Security: Distributed systems have more attack surfaces and are harder to secure. Each node must be secured, and inter-node communication must be protected.
  • Consistency: Maintaining data consistency across distributed nodes is challenging. Network partitions, delays, and failures can lead to inconsistent states.

Hardware and Software Concepts:

  • Hardware Concepts: Processors connected by a communication network. Processors may be homogeneous (same architecture) or heterogeneous. Network topologies: bus, ring, star, mesh. Communication protocols: TCP/IP, UDP, RPC.
  • Software Concepts: The distributed OS provides a unified view of the network. Transparency types:
    • Access Transparency: Uniform access to shared resources (files, printers) regardless of location.
    • Location Transparency: Access by name rather than location; the same name refers to the same resource even if its physical location changes.
    • Migration Transparency: Resources (processes, files) can be moved transparently between systems.
    • Relocation Transparency: Processes can be moved while running.
    • Replication Transparency: Multiple copies of resources exist; the system hides which copy is accessed.
    • Concurrency Transparency: Multiple users access shared resources concurrently without conflicts.
    • Failure Transparency: The system continues operating despite component failures.

Communication in Distributed Systems:

  • Message Passing: Processes exchange messages via send and receive operations. Can be blocking (waits for message) or non-blocking. Reliable or unreliable delivery. Examples: sockets, RPC.
  • Remote Procedure Call (RPC): The caller invokes a procedure on a remote server as if it were local. The stub (client-side) marshals parameters, sends the request, and unmarshals the result. The skeleton (server-side) unmarshals parameters, calls the procedure, and marshals the result. RPC hides the network details from the programmer.

Message Passing:

  • Synchronous Message Passing: The sender blocks until the receiver receives the message. Ensures the message is received before the sender continues. Used when message order and certainty are important.
  • Asynchronous Message Passing: The sender sends the message and continues immediately without waiting. The receiver processes the message later. Allows concurrent execution but requires careful handling of message ordering and buffering.

Remote Procedure Call (RPC):

  • Stub and Skeleton: Client-side stub hides the fact that the procedure is remote. Server-side skeleton unmarshals parameters and invokes the procedure.
  • Parameter Marshaling: Converting parameters into a transmittable format (serialization). Converting back (deserialization) at the receiver.
  • Example: A client calls getTime() on a remote time server. The stub packages the empty parameter list, sends the request via the network, and the server returns the time value.

Process in Distribution System:

  • Process Migration: Moving a process from one machine to another. Benefits: load balancing, fault tolerance. Challenges: preserving process state, handling open files, network transparency.
  • Process Synchronization: Coordinating execution of distributed processes. Challenges: clock differences, message ordering, distributed locks.

Clock Synchronization:

  • Importance: Accurate time coordination is essential for distributed algorithms, transaction ordering, and debugging. Logical clocks vs. physical clocks.
  • Lamport Timestamps: A logical clock mechanism that establishes a partial ordering of events without synchronized physical clocks. Each process maintains a counter; messages include the sender's timestamp, and the receiver updates its counter to max(local, received) + 1.
  • Vector Clocks: An extension of Lamport timestamps that provides a more precise partial ordering, capable of detecting concurrent events.

Key Terms

  • Distributed Operating System, Processor, Network, Transparency, Access Transparency, Location Transparency, Migration Transparency, RPC, Message Passing, Synchronous, Asynchronous, Stub, Skeleton, Lamport Timestamps, Vector Clocks, Consistency, Fault Tolerance

Unit Summary

Distributed operating systems manage multiple interconnected computers as a single system, providing transparency to hide the complexity of distribution. Key advantages include resource sharing, improved computation speed, and improved reliability. However, distributed systems introduce complexity, overhead, security challenges, and consistency issues. Transparency types (access, location, migration, etc.) hide different aspects of distribution from users and applications. Communication occurs via message passing and RPC, and clock synchronization (Lamport timestamps, vector clocks) enables coordinated operation. Understanding distributed systems is essential for modern cloud computing, distributed databases, and large-scale networked applications.

Practice Questions

Q1. What are the main advantages of a distributed operating system over a centralized system? (Answer: Resource sharing, computation speed-up through parallel processing, improved reliability (no single point of failure), and scalability (adding more processors).)

Q2. What is the difference between access transparency and location transparency? (Answer: Access transparency: uniform access to shared resources regardless of location. Location transparency: accessing resources by name rather than physical location; the same name can refer to a resource even if its location changes.)

Q3. What is RPC and how does it work? (Answer: RPC (Remote Procedure Call) allows a caller to invoke a procedure on a remote server as if it were local. The client-side stub marshals parameters, sends the request, and the server-side skeleton unmarshals and invokes the procedure, returning the result.)

Q4. What are Lamport timestamps and what do they provide? (Answer: Lamport timestamps are a logical clock mechanism that establishes a partial ordering of events in a distributed system without synchronized physical clocks. Each process maintains a counter, and messages include the sender's timestamp. The receiver updates its clock to max(local, received) + 1.)

Q5. What is the difference between synchronous and asynchronous message passing? (Answer: Synchronous: the sender blocks until the receiver receives the message. Asynchronous: the sender continues immediately after sending, without waiting for the receiver.)


Unit 10: Case Study

Teaching Hours: 2 (indicative)

DOS and Windows Operating System:

  • DOS (Disk Operating System): Microsoft's early operating system for personal computers. Character-based interface, single-tasking, limited memory management (640 KB conventional memory limit), cooperative multitasking in later versions. DOS was the foundation for Windows early versions.

    • Key Characteristics: Command-line interface (MS-DOS Prompt), flat memory model, no built-in multitasking, device drivers (SYS files), FAT file system (File Allocation Table).
    • Case Study Focus: Single-user, single-tasking nature; memory management limitations; transition to Windows.
  • Windows Operating System: Evolution from MS-DOS-based to kernel-based hybrid OS. Windows 1.x (1985) ran on top of MS-DOS. Subsequent versions (Windows 95, 98, ME, NT, XP, Vista, 7, 8, 10, 11) introduced graphical user interfaces, preemptive multitasking, protected memory model, and driver frameworks.

    • Key Evolution: Windows 95 introduced the 32-bit flat memory model, true multitasking, and the FAT32 file system. Windows NT introduced a kernel-mode/user-mode architecture similar to Unix, with the NT kernel, Win32 subsystem, and POSIX subsystem. Windows XP combined the consumer Windows 9x line with the Windows NT line.
    • Case Study Focus: Transition from cooperative to preemptive multitasking, protected memory, driver architecture, registry.

Unix Operating System:

  • Unix: Multitasking, multi-user operating system developed at Bell Labs (1970s). Written in C (portability). Introduced the concept of pipes, filters, and a hierarchical file system. Influenced almost all modern operating systems (Linux, macOS, Android).

    • Key Features: Kernel-based architecture, file everything "everything is a file," pipe and filter model, multitasking, multi-user, permission-based security, hierarchical file system.
    • Case Study Focus: Multi-user design, file system philosophy, process model, network capabilities (TCP/IP built-in).
  • Linux Operating System: Free, open-source Unix-like operating system. Created by Linus Torvalds (1991). Monolithic kernel with loadable modules. POSIX-compliant. Runs on diverse hardware from embedded devices to supercomputers.

    • Key Features: GNU userland, package management, extensive device driver support, SELinux security, virtual memory with paging, extensive networking support. Distributions: Ubuntu, Debian, Fedora, Red Hat, CentOS.
    • Case Study Focus: Open-source development model, monolithic kernel with modules, wide hardware support, security modules.

Key Terms

  • DOS, Windows, Case Study, Multitasking, Protected Memory, Registry, Unix, Linux, Open Source, Monolithic Kernel, Driver, File System, FAT, FAT32, NTFS

Unit Summary

The case study of DOS, Windows, Unix, and Linux illustrates the evolution of operating system design from single-user, single-tasking systems to modern, multi-user, preemptively multitasking systems with protected memory. DOS and early Windows were limited by the hardware constraints of the PC era, while Unix and Linux introduced multi-user, network-aware design principles that influence modern systems. Windows NT/10/11 introduced a hybrid kernel architecture combining the best of both approaches. The open-source model of Linux has driven innovation in server, desktop, and embedded operating systems.

Practice Questions

Q1. What was the main limitation of DOS? (Answer: Single-tasking, 640 KB conventional memory limit, command-line interface only, no built-in multitasking or memory protection.)

Q2. What was the key innovation of Windows 95? (Answer: Introduced the 32-bit flat memory model, true preemptive multitasking, and FAT32 file system. Marked the transition from MS-DOS-dependent to standalone 32-bit OS.)

Q3. What are the key features of the Unix operating system? (Answer: Multitasking, multi-user, kernel-based, "everything is a file," pipe and filter model, hierarchical file system, C language for portability, multi-user security.)

Q4. How does Linux differ from Unix? (Answer: Linux is open-source, freely distributable, runs on diverse hardware. Unix is proprietary (historically). Linux uses a monolithic kernel with loadable modules; Unix variants may use different kernel designs. Linux distributions package the kernel with GNU tools and desktop environments.)

Q5. Compare the kernel architectures of Windows NT and Linux. (Answer: Windows NT uses a hybrid kernel (kernel mode + user mode subsystems). Linux uses a monolithic kernel with loadable modules. Both support multiprocessing, but NT's microkernel-inspired design provides greater modularity isolation.)


References

  • Silberschatz, A., Galvin, P. B., & Gagne, G. (2018). Operating System Concepts (10th ed.). Wiley.
  • Tanenbaum, A. S., & Bos, H. (2015). Modern Operating Systems (4th ed.). Pearson.
  • Stallings, W. (2018). Operating Systems: Internals and Design Principles (9th ed.). Pearson.
  • Tanenbaum, A. S. (2001). Distributed Operating Systems. Prentice Hall.
  • Burd, J. (2005). The Design of Unix Operating Systems. Prentice Hall.
  • TU BCA Syllabus (2018). Curriculum of Bachelor of Arts in Computer Application. Tribhuvan University, Faculty of Humanities and Social Sciences.

Content Audit

  • Unit Count: 10
  • Topic Count: 73
  • Covered Topic Count: 73
  • Word Count: ~6200
  • Unresolved Items: None