0% found this document useful (0 votes)
6 views118 pages

Module 1 (Common Slide)

The document provides an overview of operating systems, detailing their functions, components, and management of resources such as processes, memory, and I/O devices. It discusses the virtualization of hardware resources, enabling multitasking and concurrency, while ensuring protection and security for users and applications. Additionally, it covers the architecture of computer systems, including single-processor and multiprocessor systems, and emphasizes the importance of persistent storage and file management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views118 pages

Module 1 (Common Slide)

The document provides an overview of operating systems, detailing their functions, components, and management of resources such as processes, memory, and I/O devices. It discusses the virtualization of hardware resources, enabling multitasking and concurrency, while ensuring protection and security for users and applications. Additionally, it covers the architecture of computer systems, including single-processor and multiprocessor systems, and emphasizes the importance of persistent storage and file management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to Operating Systems (Book 1 Ch 2 introductory

part),Operating System Services (Book 3 Ch 2) Overview of Operating


Systems and Kernels, Linux Versus Classic Unix Kernels (Book 2 Ch 1)
Process concepts: Process Creation, Process States, Data Structures,
Process API (Book 1 Ch 4, 5), Sharing processor among processes - user
and kernel modes, context switching (Book 1 Ch 6), System boot
sequence (Book 3 Ch2)
PCCST403 Case study: Linux kernel process management (Book 2, Ch 3)

Module Threads and Concurrency: Concept of a thread, Multithreading


benefits,Multithreading models (Book 3 Ch 4)
1-Syllabus Case study: The Linux Implementation of Threads (Book 2, Ch 3)
Process scheduling: Concepts and basic algorithms (Book 1 Ch 7), The
Multilevel Feedback Queue: Basic Rules (Book 1 Ch 8)
Case study: The Linux Completely Fair Scheduler (CFS) (Book 1 Ch 9,
Implementation with RB trees not required), The Linux Scheduling
Implementation,
What is an Operating System
▪ An Operating System is a program that acts as an
intermediary/interface between a user of a computer and the
computer hardware.
▪ OS goals:
▪ Control/execute user/application programs.
▪ Make the computer system convenient to use.
▪ Ease the solving of user problems.
▪ Use the computer hardware in an efficient manner.
What is an Operating System

• A modern computer consists of:


One or more processors
Main memory
Disks
Printers
Various input/output devices.
• Managing all these varied components requires a layer of software – the
Operating System (OS).
Where does the OS fit in?
•What Operating Systems Do
• Depends on the point of view
• User View: the operating system is designed mostly,
ease of use and good performance
• must keep all users happy
• Users of dedicate systems such as workstations have
dedicated resources but frequently use shared
resources from servers-resource utilization—
• Handheld computers are resource poor, optimized for
usability and battery life.
• Some computers have little or no user interface, such
as embedded computers in devices and automobiles. ,
but they and their operating systems and applications
are designed primarily to run without user
intervention.
Operating System Definition
System View:
• OS is a resource allocator
• Manages all resources
• Decides between conflicting requests for efficient and fair
resource use
• OS is a control program
1.5
• Controls execution of programs to prevent errors and improper
use of the computer.
Four Components of a Computer System
(Computer System Structure)
Computer system can be divided into four
components
◦ Hardware – provides basic computing resources
◦ CPU, memory, I/O devices.
◦ Operating system
◦ Controls and coordinates use of hardware among various
applications and users.

◦ Application programs – define the ways in which


the system resources are used to solve the computing
problems of the users.
◦ Word processors, web browsers, database systems, video games
◦ Users
◦ People, machines, other computers
Functions of an Operating System
• Process Management
• Memory Management
• Storage Management
• I/O Management
• Protection and Security
Process Management
• A process is program in execution.
• Eg: A word-processing program being run by an individual user on
a PC
• A process needs certain resources to accomplish its task.
• CPU time
• memory
• files
• I/O devices.
• These resources are either given to the process when it is created or
allocated to it while it is running.
Process Management
• The operating system is responsible for the following process
management activities :
• Scheduling processes and threads on the CPUs
• Creating and deleting both user and system processes
• Suspending and resuming processes
• Providing mechanisms for process synchronization
• Providing mechanisms for process communication
Memory Management
• Main memory is the only large storage device that the CPU is
able to address and access directly.
• For a program to be executed, it must be mapped to absolute
addresses and loaded into memory.
• As the program executes, it accesses program instructions and
data from memory by generating these absolute addresses.
• When the program terminates, its memory space is declared
available, and the next program can be loaded and executed.

• To improve both the utilization of the CPU and the speed of


the computer’s response to its users, general-purpose
computers must keep several programs in memory, creating a
need for memory management.
Memory Management
• The operating system is responsible for the following memory
management activities :
• Keeping track of which parts of memory are currently being used and who is
using them
• Deciding which processes (or parts of processes) and data to move into and out
of memory
• Allocating and deallocating memory space as needed
I/O Management
• One of the purposes of an operating system is to hide the
peculiarities of specific hardware devices from the user.
• Every operating systems has an I/O subsystem for managing its I/O
devices.
Protection and Security

• If a computer system has multiple users and allows the concurrent


execution of multiple processes, then access to data must be regulated.
• There must be mechanisms to ensure that files, memory segments, CPU,
and other resources can be operated on by only those processes that have
gained proper authorization from the operating system.
• For example, memory-addressing hardware ensures that a process can
execute only within its own address space.
• The timer ensures that no process can gain control of the CPU without
eventually relinquishing control.
Computer-System Architecture

• A computer system can be organized in a number of different ways, which we can categorize roughly
according to the number of general-purpose processors used.
• Most systems use a single general-purpose processor .
• Most systems have special-purpose processors as well
• Multiprocessors systems growing in use and importance
Single-Processor Systems
• On a single processor system, there is one main CPU capable
of executing a general-purpose instruction set, including
instructions from user processes.

• Almost all single processor systems have other special-purpose


processors like device-specific processors, such as disk,
keyboard, and graphics controllers.

• All of these special-purpose processors run a limited


instruction set and do not run user processes.

• Sometimes, they are managed by the operating system, in that


the operating system sends them information about their next
task and monitors their status.
Single-Processor Systems
• In some other systems special-purpose processors are
low-level components built into the hardware.
• The operating system cannot communicate with these
processors; they do their jobs autonomously.
Multiprocessor Systems
• Two or more processors in close communication, sharing the
computer bus and sometimes the clock, memory, and
peripheral devices.
• Multiprocessor systems have three main advantages:
1. Increased throughput
• By increasing the number of processors, more work done in less
time.
Multiprocessor Systems
• The multiple-processor systems in use today are of two types.

• Asymmetric multiprocessing
• Each processor is assigned a specific task.
• A boss processor controls the system; the other
processors either look to the boss for instruction or have
predefined tasks.
• This scheme defines a boss–worker relationship.
• The boss processor schedules and allocates work to the
worker processors.
Multiprocessor Systems
• Symmetric multiprocessing (SMP)
• Each processor performs all tasks within the operating system.
• All processors are peers; no boss–worker relationship exists
between processors.

• Each processor has its own set of registers, as well as a private


or local cache.
• All processors share physical memory.
Multiprocessor Systems
• Multiprocessing adds CPUs to increase computing power.
• The definition of multiprocessor has evolved over time and now includes
multicore systems, in which multiple computing cores reside on a single
chip.
• They can be more efficient than multiple chips with single cores because
on-chip communication is faster than between-chip communication.
• One chip with multiple cores uses significantly less power than
multiple single-core chips.
Dual-core design with two cores on the same pro
cessor chip
Clustered Systems
• A type of multiprocessor system is a clustered system, which
gathers together multiple CPUs.
• Clustered systems differ from the multiprocessor systems in
that they are composed of two or more individual systems or
nodes joined together.
• Each node may be a single processor system or a multicore
system.
• Clustered computers share storage and are closely linked via a
local-area network LAN or a faster interconnect, such as
InfiniBand.
• Clustering is usually used to provide high-availability service.
Clustered Systems
• Service will continue even if one or more systems in the
cluster fail.
• A layer of cluster software runs on the cluster nodes.
• Each node can monitor one or more of the others (over the
LAN).
• If the monitored machine fails, the monitoring machine can
take ownership of its storage and restart the applications that
were running on the failed machine.
• The users and clients of the applications see only a brief
interruption of service.
Clustered Systems
Introduction to Operating Systems
•A running program performs one fundamental activity:
• It executes instructions.
•Instruction Execution Cycle :
• Fetch: Processor retrieves the next instruction from memory.
• Decode: Determines what the instruction means (operation type).
• Execute: Executes the instruction. (it does the thing that it is supposed to do)
• Performs the operation:
• Arithmetic (e.g., add two numbers) ,Memory access
• Conditional checks , Function calls or jumps
• Move to Next Instruction:
• Process continues until the program completes.
• The above cycle describes the Von Neumann architecture- A model where
instructions and data are both stored in memory and processed sequentially.
• Modern processors do many things underneath the hood to make programs
run faster, e.g., executing multiple instructions at once, and even issuing and
completing them out of order.
• While programs run, many background activities happen to make the system
easy and safe to use.
• There is a body of software, in fact, that is responsible for making it easy to
run programs (even allowing you to seemingly run many at the same time),
allowing programs to share memory, enabling programs to interact with
devices. That body of software is called the operating system (OS).
• Operating System Responsibilities/functions:
• Process Management
Allows multiple programs to run seemingly at the same time (multitasking).
• Memory Management
Ensures programs share memory safely and efficiently.
• Device Management
Enables programs to interact with hardware devices (keyboard, disk, network, etc.).
• Abstraction & Simplification
OS hides complex hardware details and provides simple interfaces to users and programs.
•The primary way the OS does this is through a general technique
that we call virtualization.
• That is, the OS takes a physical resource (such as the processor,
or memory, or a disk) and transforms it into a more general,
powerful, and easy-to-use virtual form of itself.
•The OS uses virtualization to convert physical hardware (CPU,
memory, disk) into virtual, more flexible, and easy-to-use
versions
•Because of this, the OS is often called a virtual machine.
• Virtualization makes one physical resource appear like multiple logical
resources, enabling sharing and convenience.
• To use these virtual machine, the OS provides interfaces (APIs).
• Applications request services (run a program, allocate memory, open files)
through system calls
• A typical OS provides hundreds of system calls.
• These system calls collectively act as a standard library for applications.
OS as a Resource Manager
Virtualization allows many programs to:
◦ Share the CPU (process management)
◦ Share memory (memory management)
◦ Share devices like disks, printers, etc. (device management)
◦ Because it controls and allocates these resources, the OS is also known as a
resource manager.
◦ Each of the CPU, memory, and disk is a resource of the system;
◦ The OS manages resources with goals such as efficiency, fairness, and
performance.
Role of OS
[Link] the CPU
• The operating system creates the illusion that many programs are running at the same time even
though the computer has only one processor.
• It does this with hardware support by virtualizing the CPU, making one physical processor
appear as many virtual CPUs.
• This allows multiple programs to seem like they are executing simultaneously.
• To run or control these programs, the OS provides interfaces and APIs that users and applications
call to communicate their requests to the system.
• The presence of many programs running together also introduces challenges, such as deciding
which program should run at a given moment.
• These decisions are handled by OS policies, which define how resources are shared and
scheduled.
• Thus, the OS acts as a resource manager, ensuring efficient and fair use of the CPU while
supporting multiple concurrent programs.
Running Many Programs At Once
2. Virtualizing Memory
• When multiple instances of the same program run, each one appears to use the same
memory address, yet they do not interfere with one another.
• This is because the operating system virtualizes memory.
• Every running program is given its own private virtual address space, which makes it
seem as if it has exclusive access to memory.
• The OS maps each process’s virtual addresses to the actual physical memory of the
machine.
• As a result, one program’s memory accesses do not affect the memory of any other
program or the OS.
• Although physical memory is shared, the OS manages it carefully to maintain
isolation and protection.
• This mechanism of mapping and isolation is a core part of memory virtualization.
Concurrency
• Concurrency in an operating system refers to the ability of the system to allow
multiple tasks to make progress at the same time.
• These tasks may be processes, threads, or parts of a program that overlap in
execution.
• Even on a single CPU, concurrency is achieved by rapidly switching between
tasks, creating the illusion that they are running simultaneously.
• The OS enables concurrency through mechanisms such as context switching,
process scheduling, and thread management.
•However, concurrency introduces challenges.
•When multiple tasks access shared data or resources at the same time, problems like race
conditions, deadlocks, and starvation can occur.
• To handle these issues safely, the OS provides synchronization tools such as locks, semaphores,
monitors, and condition variables
•.Concurrency is a key part of modern systems because it increases performance, improves
resource utilization, and allows programs to be more responsive.
•It is central to how operating systems manage CPUs, memory, devices, and running programs.
Persistence
•Persistence means the ability of a system to store data safely for long periods of
time.
•Data stored in main memory (DRAM) is volatile:
• Data is lost when power fails
• Data is lost during system crashes
•Hence, systems require persistent storage to protect important user data.
•Persistence is achieved through I/O (Input/Output) devices.
• Common persistent storage devices:
• Hard Disk Drives (HDDs) – traditional storage
• Solid State Drives (SSDs) – faster modern storage
• These devices store data even when the system is powered off.
•The File System is the OS software responsible for:
•Storing files reliably on disks
•Managing file access efficiently
•It ensures that:
•User-created files are stored safely
•Data can be retrieved when needed.
•The OS does NOT create separate disks for each program
•Files are shared between processes
•Example workflow:
•A text editor creates a source file (main.c)
•A compiler reads the file and creates an executable
•The executable is then run as a new program
•This shows how files act as shared data between programs
• Three calls into the operating system.
• The first, a call to open(), opens the file and creates it;
• the second, write(), writes some data to the file;
• the third, close(), simply closes the file thus indicating the program won’t be writing
any more data to it.
• These system calls are routed to the part of the operating system called the file
system.
Design goals
• An operating system virtualizes physical resources such as the CPU, memory, and
disk, manages concurrency, and stores data persistently.
• To build such a system effectively, certain goals guide its design.
• A major goal is to create abstractions that make the system simple and convenient to
use, hiding complex hardware details from users and applications.
• Another key goal is high performance, which means providing virtualization and
other OS features with minimal overhead in time and space.
• The OS must also provide protection and isolation so that one program cannot harm
another, and no application can damage the OS itself.
• Isolation is essential when multiple programs run simultaneously.
• Finally, the OS must ensure reliability, because if the operating system fails, all
running applications fail.
• Therefore, maintaining continuous and dependable operation is a critical
objective in OS design.
operating system services
An operating system(OS) provides an essential environment for executing programs.
It offers various services that help both users and programs run efficiently.
These services may vary between different operating systems, but commonly include program
execution, input/output operations, file-system manipulation, communication, error detection,
and resource allocation.
By offering these services, the OS ensures smooth, secure, and efficient operation of the entire
computer system.
Operating systems provide several key services to ensure efficient and secure execution of
programs:
User Interface (UI): Most OSes offer a user interface such as a GUI, which uses windows,
icons, menus, mouse, and keyboard. Mobile devices use touch interfaces, while many systems
also support command-line interfaces (CLI) for text-based commands.
Program Execution: The OS loads programs into memory, runs them, and handles their
termination—whether normal or due to errors.
I/O Operations: Programs often need to perform input/output operations using files or devices.
Since users cannot directly control hardware, the OS provides safe and efficient I/O handling.
File-System Manipulation: The OS enables creating, deleting, reading, and
writing files and directories. It also manages file permissions and may support
multiple file systems for different needs.
Communication: Processes may need to share data either within the same
system or across a network. The OS supports communication via shared memory
or message passing.
Error Detection: The OS continuously monitors the system for errors in
hardware, devices, and programs. It responds appropriately to maintain system
stability—by halting the system, terminating faulty programs, or reporting errors.
Additional Operating System Services
Resource Allocation: In a multiprogramming environment, the OS allocates resources such
as CPU time, memory, storage, and I/O devices to different processes. It uses scheduling
algorithms and allocation routines to ensure efficient and fair resource usage.
Logging (Accounting):The OS keeps records of resource usage by programs—such as CPU
time, memory usage, and I/O operations. These logs help in billing users, analyzing system
performance, and planning system upgrades or configurations.
Protection and Security:The OS ensures that each process operates safely without interfering
with others. It protects data and system resources through access control, authentication, and
secure communication, especially in multiuser or networked environments.
Overview of Operating Systems and Kernels
Overview of Operating Systems and Kernels
This topic explains what an operating system (OS) is and how the kernel forms its core.
OS refers to the system software that manages hardware and provides basic services to
applications.
The kernel is the most important internal part of the OS—it controls hardware, manages
memory, schedules processes, handles interrupts, and coordinates system resources.
Because of its critical role, the kernel runs in a special privileged mode called kernel space,
where it has full access to the machine.
Normal applications run in user space, which is restricted to protect the system.

Applications cannot directly access hardware, so they communicate with the kernel through
system calls.

When an application calls a function from a library (like printf()), the library may eventually
make a system call (like write()) to request the kernel to perform an action such as outputting
text to the console.

When a system call is executed, the CPU switches from user mode to kernel mode, allowing
the kernel to safely complete tasks on behalf of the application.
This relationship—applications requesting services through system calls and the
kernel executing them—forms the fundamental working of an operating system.

The kernel ensures safety, resource management, and controlled access to


hardware, while applications run independently in user space and rely on the OS
to perform essential operations.
The diagram a shows how applications, the kernel, and hardware relate.

User programs run in user space and cannot directly touch hardware, instead they call the
system call interface (often via library functions).

Those system calls enter kernel space, where kernel subsystems and device drivers run with
full privileges.

Kernel subsystems implement services such as process scheduling and memory management,
while device drivers translate kernel requests into hardware actions.

Together this layered design keeps user programs isolated and lets the kernel safely manage
resources and hardware on their behalf.
Kernel also handles interrupts, the asynchronous signals from hardware (for example, a
keyboard telling the system a key was pressed).

Each interrupt has a number that identifies a specific interrupt handler inside the kernel; the
handler runs, processes the event (e.g., read keyboard buffer), and returns control.

For correctness and speed, interrupt handlers often run in a special interrupt context (not in a
regular process context) and the kernel can temporarily disable interrupts to synchronize access
to shared data.

Applications request services through system calls, and hardware events are handled by
interrupt handlers — both mechanisms let the kernel coordinate safe, efficient interaction
between software and hardware.
OS provides process abstraction
When you run an exe file, the OS creates a process = a running program

• OS timeshares CPU across multiple processes: virtualizes CPU

•OS has a CPU scheduler that picks one of the many active processes to execute on a CPU

Policy: which process to run


Mechanism: how to “context switch” between processes
What constitutes a process?
A unique identifier (PID)
• Memory image
Code & data (static)
Stack and heap (dynamic)
• CPU context: registers
Program counter
Current operands
Stack pointer
• File descriptors–
Pointers to open files and devices
How does OS create a process?
• Allocates memory and creates memory image
– Loads code, data from disk exe
– Creates runtime stack, heap
• Opens basic files
– STD IN, OUT, ERR

• Initializes CPU registers registers


-PC points to first instruction
States of a process
• Running: currently executing on CPU

• Ready: waiting to be scheduled

• Blocked: suspended, not ready to run


– Why? Waiting for some event, e.g., process issues a read from disk
–When is it unblocked? Disk issues an interrupt when data is ready

• New: being created, yet to run

• Dead: terminated
OS data structures
• OS maintains a data structure (e.g., list) of all active processes active processes

• Information about each process is stored in a process control block (PCB) process control block (PCB)
– Process identifier
– Process state
– Pointers to other related processes (parent)
– CPU context of the process (saved when the process is suspended)
– Pointers to memory locations
– Pointers to open files
Kernel Data Structures
Kernel Data Structures
Fundamental data structures used extensively in operating systems
1. Lists, Stacks, and Queues
⚫ A list represents a collection of data values as a sequence.
⚫ The most common method for implementing this structure is a linked list, in which items
are linked to one another.
⚫ Linked lists are of several types:
⚫ Singly linked list:Each item points to its successor

⚫ Doubly linked list: A given item can refer either to its predecessor or to its successor.
Kernel Data Structures

Circularly linked list: Last element in the list refers to the first element.
Kernel Data Structures
Stack
⚫ A stack is a sequentially ordered data structure that uses the last in, first out (LIFO)
principle for adding and removing items, meaning that the last item placed onto a
stack is the first item removed.
⚫ The operations for inserting and removing items from a stack are known as push and
pop, respectively.
⚫ An operating system often uses a stack when invoking function calls.
⚫ Parameters, local variables, and the return address are pushed onto the stack when a
function is called; returning from the function call pops those items off the stack.
Kernel Data Structures
Queue
⚫ A queue is a sequentially ordered data structure that uses the first in, first out (FIFO)
principle: items are removed from a queue in the order in which they were inserted.
⚫ Queues are also quite common in operating systems—jobs that are sent to a printer
are typically printed in the order in which they were submitted,
⚫ Tasks that are waiting to be run on an available CPU are often organized in queues
Kernel Data Structures
Trees
⚫ A tree is a data structure that can be used to represent data hierarchically.
⚫ Data values in a tree structure are linked through parent–child relationships.
⚫ In a general tree, a parent may have an unlimited number of children.
⚫ In a binary tree, a parent may have at most two children, which we term the left child
and the right child.
⚫ A binary search tree additionally requires an ordering between the parent’s two
children in which le f t child <= right child.
Kernel Data Structures

⚫ An operating system maintains a disk's file system as a tree, where file folders act as
tree nodes: The tree structure is useful because it easily accommodates the creation
and deletion of folders and files.
Kernel Data Structures
Hash Functions and Maps
⚫ A hash function is a function that can be used to map data of arbitrary size to data of
fixed size.
⚫ A hash function takes data as its input, performs a numeric operation on this data, and
returns a numeric value.
⚫ This numeric value can then be used as an index into a table (typically an array ) to
quickly retrieve the data.
Kernel Data Structures
⚫ One potential difficulty with hash functions is that two inputs can result in the same
output value that is, they can link to the same table location.
⚫ We can accommodate this hash collision by having a linked list at that table location
that contains all of the items with the same hash value.
Kernel Data Structures
Hash Map

⚫ One use of a hash function is to implement a hash map, which associates (or maps)
[key:value] pairs using a hash function.
⚫ For example, we can map the key operating to the value system.
⚫ Once the mapping is established,we can apply the hash function to the key to obtain
the value from the hash map
Kernel Data Structures
⚫ For example, suppose that a user name is mapped to a password.
⚫ Password authentication then proceeds as follows: a user enters his user name and
password.
⚫ The hash function is applied to the user name, which is then used to retrieve the
password. The retrieved password is then compared with the password entered by the
user for authentication.
Kernel Data Structures
Bitmaps
⚫ A bitmap is a string of n binary digits that can be used to represent the status of n
items.
⚫ Eg:Suppose we have several resources, and the availability of each resource is
indicated by the value of a binary digit:
0 -resource is available
1 - resource is unavailable (or vice-versa).
⚫ The value of the ith position in the bitmap is associated with the ith resource.
⚫ As an example, consider the bitmap 001011101 ,that means resources 2, 4, 5, 6, and
8 are unavailable; resources 0, 1, 3, and 7 are available
Kernel Data Structures
⚫ Bitmaps are commonly used when there is a need to represent the availability of a
large number of resources.
⚫ Eg: A medium-sized disk drive might be divided into several thousand individual
units, called disk blocks. A bitmap can be used to indicate the availability of each disk
block
Process creation in UNIX systems.
A parent process creates one or more child processes.
◦ These child processes can further create other processes, forming a process tree.
◦ Each process is uniquely identified and managed using a Process Identifier (PID).
Resource Sharing
• A parent and child process may share resources in different ways:
• Parent and child share all resources
• Child shares a subset of the parent’s resources
• Parent and child share no resources

Execution
• Parent and child processes may execute concurrently
• The parent process may wait until the child process terminates
• Address Space
• The child process may be a duplicate of the parent process.
• The child process may have a new program loaded into its address space.
Process related system calls (in Unix)
• fork() creates a new child process
• All processes are created by forking from a parent.
• OS(kernel) starts init() process after boot up, which forks other processes.
• The init() process is ancestor of all processes, including shell/terminal
• exec() makes a process execute a given executable.
•Used after fork()
•Replaces the process’s memory space with a new program.
• exit() terminates a process
• wait() causes a parent to block until child terminates
• Many variants of the above system calls exist in language libraries with
different arguments.
4
The fork()System Call

◦ fork() returns 0 to the child, child’s PID to the parent, and −1 on failure.

•The child sees rc = 0


•The parent sees rc = child’s PID
•Both processes execute the code after fork()

•The child sees rc = 0


•The parent sees rc = child’s PID
•Both processes execute the code after fork()
Process creation: fork
• Parent process calls “fork” system call to create (spawn) a new process
• New child process created with new PID
• Memory image of parent is copied into that of child
• Parent and child run different copies of same code

Parent memory image copied to create


child memory image

Image credit: OSTEP


What happens after fork?
• Parent and child resume execution in their copies of the code
• Child starts executing with a return value of 0 from fork
• Parent resumes executing with a return value equal to child PID
• Parent and child run independently
• Any changes in parent’s data after fork does not impact child

int ret = fork() Child resumes int ret = fork()


if(ret == 0) { here if(ret == 0) {
print “I am child” Parent resumes print “I am child”
} here }
else if(ret > 0) { else if(ret > 0) {
print “I am parent” print “I am parent”
} }
Example code with fork
• Parent and child run independently and print to screen
• Order of execution of parent and child can vary

8
Exit system call
• When a process finishes execution, it calls exit system call to terminate
• OS switches the process out and never runs it again

• Exit is automatically called at end of main

• Exiting
process cannot clean up its memory, and memory must be freed up by
someone else
• Terminatedprocess exists in a zombie state
• How are zombies cleaned up?
Wait system call
• Parent calls wait system call to clean up memory
of a zombie child.
• Wait cleans up memory of one terminated child and
returns in parent process. …
int ret = fork()
• If child still running, wait system call blocks if(ret == 0) {
print “I am child”
parent until child exits. exit()
• If child terminated already, wait reaps child and returns }
else if(ret > 0) { print
immediately “I am parent”
wait()
• If parent with no child calls wait, it returns }
immediately without reaping anything. …
Here parent to wait for a child process to finish what it has
been doing.
This task is accomplished with the wait() system call
Example code with fork and wait
• Order of printing of child and parent is deterministic now
• Why? Parent waits until child prints and exits, then prints
fork() returns 0 to the child, child’s PID to the parent
Exec system call
•Isn’t it impractical to run the same code in all
processes? …
int ret = fork();
• Sometimes parent creates child to do similar work..
if(ret == 0) {
• .. but other times, child may want to run different code exec(“some_executable”)
}
•Child process uses “exec” system call to get a new else if(ret > 0) {
“memory image” print “I am parent”
}
• Allows a process to switch to running different code …
• Exec system call takes another executable as argument
• Memory image is reinitialized with new executable, new code, data,
stack, heap, …
The child process replaces itself with
the wc program, which counts lines,
words, and bytes in p3.c.

17
Image credit: OSTEP
Example code with exec
• Many variants of exec system call (execvp used in example), which differ in the
arguments provided .
• If exec successful, child gets new memory image, never comes back to the
code in old memory image after exec
• Print statement after exec doesn’t run if exec successful
• If exec unsuccessful, reverts back to original memory image

Image credit: OSTEP


Example code with exec
• Many variants of exec system call (execvp used in example), which differ in the
arguments provided .
• If exec successful, child gets new memory image, never comes back to the
code in old memory image after exec
• Print statement after exec doesn’t run if exec successful
• If exec unsuccessful, reverts back to original memory image

Image credit: OSTEP


Example code
with fork int ret = fork()
int x = 1
• What values of x are printed? if(ret == 0) {
print “I am child”
• Parent and child both start with their own
x = x+1
independent copies of variable x in their
print x
memory images
}
• Child increments its copy of x, prints 2 else if(ret > 0) {
• Parent decrements its copy of x, prints 0 print “I am parent”
x = x -1
print x
}

Image credit: CSAPP


Rule:
#include <stdio.h>
#include <unistd.h>

int main() {

fork();
fork();

printf("Hello\n");
return 0;
}
| Fork count | Total processes | Hello printed |
| ---------- | --------------- | ------------- |
| 1 fork |2 |2 |
| 2 forks | 4 |4 |
| 3 forks | 8 |8 |
Example code with nested fork
fork()
fork()
• Total 4 processes (1 parent + 3 child) print hello
exit
• Hello printed 4 times

Image credit: CSAPP


Process API
Process APIs, in some form, are available on any modern operating system.
The Process API is the set of operating system interfaces used to manage processes. It
allows users and programs to control the life cycle and behavior of processes.
⚫ Create:
The Process API provides system calls to create a new process when a command is
executed or an application is launched.

• Destroy:
The Process API allows processes to be terminated either normally or forcefully using
system calls when a process misbehaves or is no longer needed.

• Wait:
Using the Process API, a process can wait for another process (usually a child process) to
finish execution before continuing.
• Miscellaneous Control:
The Process API supports additional controls such as suspending a process and
resuming it later, helping in efficient multitasking.

• Status:
The Process API provides mechanisms to obtain process information like execution
state, CPU usage, and runtime details.

These Process API functions enable the operating system to create, control, synchronize,
and monitor processes effectively.
Sharing processor among process(Virtualizing CPU)
● To virtualize the CPU, the operating system shares a single physical CPU among
multiple processes so that they appear to run at the same time.
● The OS runs one process for a short time, then switches to another process, and
continues this cycle. This rapid switching creates the illusion that all processes are
running simultaneously.
● CPU virtualization allows each process to believe it has its own CPU, improving
system responsiveness and multitasking.
• Challenge 1 – Performance:
The OS must implement CPU sharing efficiently. Frequent switching between processes
should not introduce too much overhead, or system performance will degrade.

• Challenge 2 – Control:
The OS must retain full control of the CPU. It should prevent any single process from
running forever or accessing unauthorized resources.
Basic Technique: Limited Direct Execution
Limited Direct Execution is a technique used by operating systems to virtualize the CPU efficiently. In this
approach, the OS allows a user program to run directly on the CPU to achieve high performance, instead of
interpreting or emulating every instruction.
However, direct execution alone causes two major problems:

1)Protection – The OS must prevent user programs from performing illegal operations (e.g., accessing hardware
directly).

2)Control – The OS must be able to stop a running process and switch to another to support time-sharing.

To solve this, the OS adds limits:

-User mode and kernel mode to restrict privileged instructions

-System calls to safely request OS services

-Timer interrupts to regain control of the CPU for context switching


Problem #1: Restricted Operations
Direct execution is fast because the program runs natively on the CPU without OS
intervention for every instruction. However, this creates a key problem: user processes
cannot be allowed to perform restricted operations.

Operations such as:

● Performing I/O (disk, keyboard, network)

● Accessing or modifying hardware

● Allocating CPU or memory beyond limits


To handle this, the OS uses:

Dual-mode operation:

● User mode → restricted access


● Kernel mode → full privileges
● System calls: user programs request restricted operations safely by switching to
kernel mode
● Hardware support: prevents execution of privileged instructions in user mode
Trap
A trap is a controlled transfer of execution from user mode to kernel mode.
It occurs when:

A user program makes a system call

An exception or error happens

Traps allow user programs to request restricted operations safely.

Trap Table
The trap table is a data structure maintained by the OS that stores addresses of kernel routines
(trap handlers).
Each system call or exception has an entry in the trap table, and the hardware uses it to jump to
the correct OS handler.
Problem #2: Switching Between Processes
When a process is running on the CPU, the OS is not running. Therefore, the OS cannot
directly stop a process and switch to another one. This makes process switching difficult
in pure direct execution.

[Link] Approach
One early solution is cooperative scheduling, used in older systems (e.g., early
Macintosh, Xerox Alto).

The OS trusts processes to behave properly.

A running process voluntarily gives up the CPU so the OS can schedule another
process.
How the OS Regains Control?.

System calls: Processes frequently call the OS (e.g., file I/O, process creation).

Yield system call: An explicit call where a process gives up the CPU.

Traps due to errors: Illegal operations (divide by zero, invalid memory access) generate
a trap, returning control to the OS.
2.A Non-Cooperative Approach: The OS Takes Control

● OS cannot depend on processes to give up CPU voluntarily.


● Infinite loops can block OS control in cooperative systems.
● Timer interrupt solves this problem.
● Timer generates interrupts at fixed intervals.
● Interrupt pauses the running process and transfers control to the OS.
● OS can then preempt the process and run another one.
● Timer and interrupt handlers are set during boot time (privileged).
● Hardware saves process state; OS restores it using return-from-trap.
Saving and Restoring Context(Context Switching)
❏ When the OS regains control through a system call or a timer interrupt, it must decide
whether to keep running the current process or switch to another. This decision is made by
the scheduler.
❏ If a switch is needed, the OS performs a context switch.

❏ During a context switch, the OS saves the CPU state of the current process, such as
registers, program counter, and kernel stack pointer, and restores the saved state of the next
process.

❏ The switch is done by low-level code that changes the kernel stack from the old process to
the new one. After this, when the return-from-trap instruction is executed, the CPU
resumes execution of the new process instead of the old one.

❏ There are two kinds of state saving involved. First, when a timer interrupt occurs, the
hardware automatically saves the user-level state of the running process on its kernel stack.

❏ Second, when the OS switches processes, it explicitly saves and restores the kernel-level
state in the process control structures. This completes the context switch and allows another
process to run.
Building and Booting an Operating System
It is possible to design, code, and implement an operating system specifically for one
specific machine configuration.
More commonly, however, operating systems are designed to run on any of a class of
machines with a variety of peripheral configurations.
If you are generating (or building) an operating system from scratch, you must follow
these steps:
[Link] the operating system source code (or obtain previously written
source code).
2. Configure the operating system for the system on which it will run.
3. Compile the operating system.
4. Install the operating system.
5. Boot the computer and its new operating system.
System Boot
After an operating system is generated, it must be made available for use by
the hardware. But how does the hardware know where the kernel is or how to
load that kernel? The process of starting a computer by loading the kernel is
known as booting the system. On most systems, the boot process proceeds as
follows:
1. A small piece of code known as the bootstrap program or boot loader
locates the kernel.
2. The kernel is loaded into memory and started.
3. The kernel initializes hardware.
4. The root file system is mounted.
Boot Proccess-types
[Link] Booting (BIOS-based):

On power-on, a small boot loader in BIOS (firmware) runs.

BIOS loads a second boot loader from a fixed disk location called the boot block.

The boot-block program is small (fits in one disk block).

It either:

Loads the entire operating system, or

Loads the rest of the bootstrap program using known disk address and length.
[Link] (Unified Extensible Firmware Interface):

Modern replacement for BIOS.

Advantages:

Better support for 64-bit systems.

Supports larger disks.

Acts as a single, complete boot manager.

Faster than multistage BIOS booting.


[Link] Program Functions (BIOS or UEFI):

❖ Loads the kernel into memory.


❖ Runs diagnostics:
❖ Checks memory and CPU.
❖ Detects connected devices.
❖ Initializes system components: CPU registers, Device controllers, Main memory.
❖ Starts the OS and mounts the root file system.
❖ System is considered running only after this step.
[Link] (Grand Unified Bootloader):

Open-source boot loader for Linux and UNIX.

Loads boot parameters from a GRUB configuration file.

Allows:

Changing kernel parameters at boot time.

Selecting among multiple kernels.


[Link] and Diagnostic Boot Modes:

Most OS (Windows, Linux, macOS, iOS, Android) can be in two boot modes

-Recovery mode.

-Single-user mode.

Used for:

❏ Hardware diagnostics.

❏ Repairing corrupt file systems.

❏ Reinstalling the operating system.

You might also like