OS Notes
OS Notes
Operating System a type of system software. It basically manages all the resources of the
computer. An operating system acts as an interface between the software and different
parts of the computer or the computer hardware. The operating system is designed in such
a way that it can manage the overall resources and operations of the computer.
Operating System is a fully integrated set of specialized programs that handle all the
operations of the computer. It controls and monitors the execution of all other programs
that reside in the computer, which also includes application programs and other system
software of the computer. Examples of Operating Systems are Windows, Linux, Mac OS,
etc.
An Operating System (OS) is a collection of software that manages computer hardware
resources and provides common services for computer programs.
An operating system is system software that acts as an intermediary between a user of a
computer and the computer hardware. It is software that manages the computer hardware
and allows the user to execute programs in a convenient and efficient manner.
The user’s view of the operating system depends on the type of user.
If the user is using standalone system, then OS is designed for ease of use and high
performances. Here resource utilization is not given importance.
If the users are at different terminals connected to a mainframe or minicomputers, by
sharing information and resources, then the OS is designed to maximize resource
utilization. OS is designed such that the CPU time, memory and i/o are used
efficiently and no single user takes more than the resource allotted to them.
If the users are in workstations, connected to networks and servers, then the user
have a system unit of their own and shares resources and files with other systems.
Here the OS is designed for both ease of use and resource availability (files).
Other systems like embedded systems used in home device (like washing m/c) &
automobiles do not have any user interaction. There are some LEDs to show the
status of its work
Users of hand-held systems, expects the OS to be designed for ease of use and
performance per amount of battery life
System Views:Operating system can be viewed as a resource allocator and control program.
Resource allocator – The OS acts as a manager of hardware and software
resources. CPU time, memory space, file-storage space, I/O devices, shared files
etc. are the different resources required during execution of a program. There can be
conflicting request for these resources by different programs running in same system.
The OS assigns the resources to the requesting program depending on the priority.
Control Program – The OS is a control program and manage the execution of user
program to prevent errors and improper use of the computer.
Managing Input-Output unit: The operating system also allows the computer to manage
its own resources such as memory, monitor, keyboard, printer, etc. Management of these
resources is required for effective utilization. The operating system controls the various
system input-output resources and allocates them to the users or programs as per their
requirements.
Multitasking: The operating system manages memory and allows multiple programs to
run in their own space and even communicate with each other through shared memory.
Multitasking gives users a good experience as they can perform several tasks on a
computer at a time.
A platform for other software applications: Different application programs are needed
by users to carry out particular system tasks. These applications are managed and
controlled by the OS to ensure their effectiveness. It serves as an interface between the
user and the applications, in other words.
Controls memory: It helps in controlling the computer‟s main memory. Additionally, it
allows and deallocates memory to all tasks and applications.
Looks after system files: It helps with system file management. As far as we are aware,
all of the data on the system exists as files. It facilitates simple file interaction.
Provides Security: It helps to maintain the system and applications safe through the
authorization process. Thus, the OS provides security to the system.
System Call
A system call is a programmatic way in which a computer program requests a service
from the kernel of the operating system it is executed on. A system call is a way for
programs to interact with the operating system. A computer program makes a system
call when it requests the operating system‟s kernel.
System call provides the services of the operating system to the user programs via the
Application Program Interface(API). It provides an interface between a process and an
operating system to allow user-level processes to request services of the operating
system. System calls are the only entry points into the kernel system. All programs
needing resources must use system calls.
What is a System Call?
A system call is a mechanism used by programs to request services from the operating
system (OS). In simpler terms, it is a way for a program to interact with the underlying
system, such as accessing hardware resources or performing privileged operations.
A user program can interact with the operating system using a system call. A number of
services are requested by the program, and the OS responds by launching a number of
systems calls to fulfill the request. A system call can be written in high-level languages like
C or Pascal or in assembly language. If a high-level language is used, the operating
system may directly invoke system calls, which are predefined functions.
A system call is initiated by the program executing a specific instruction, which triggers a
switch to kernel mode, allowing the program to request a service from the OS. The OS
then handles the request, performs the necessary operations, and returns the result back
to the program.
System calls are essential for the proper functioning of an operating system, as they
provide a standardized way for programs to access system resources. Without system
calls, each program would need to implement its methods for accessing hardware and
system services, leading to inconsistent and error-prone behavior.
Services Provided by System Calls
Process Creation and Management
Main Memory Management
File Access, Directory, and File System Management
Device Handling(I/O)
Protection
Networking, etc.
Process Control: end, abort, create, terminate, allocate, and free memory.
File Management: create, open, close, delete, read files, etc.
Device Management
Information Maintenance
Communication
Open(): Accessing a file on a file system is possible with the open() system call. It gives
the file resources it needs and a handle the process can use. A file can be opened by
multiple processes simultaneously or just one process. Everything is based on the
structure and file system.
Read(): Data from a file on the file system is retrieved using it. In general, it accepts three
arguments:
A description of a file.
A buffer for read data storage.
How many bytes should be read from the file Before reading, the file to be read could
be identified by its file descriptor and opened using the open() function.
Wait(): In some systems, a process might need to hold off until another process has
finished running before continuing. When a parent process creates a child process, the
execution of the parent process is halted until the child process is complete. The parent
process is stopped using the wait() system call. The parent process regains control once
the child process has finished running.
Write(): Data from a user buffer is written using it to a device like a file. A program can
produce data in one way by using this system call. generally, there are three arguments:
A description of a file.
A reference to the buffer where data is stored.
The amount of data that will be written from the buffer in bytes.
Fork(): The fork() system call is used by processes to create copies of themselves. It is
one of the methods used the most frequently in operating systems to create processes.
When a parent process creates a child process, the parent process‟s execution is
suspended until the child process is finished. The parent process regains control once the
child process has finished running.
Exit(): A system call called exit() is used to terminate a program. In environments with
multiple threads, this call indicates that the thread execution is finished. After using the
exit() system function, the operating system recovers the resources used by the process.
The kernel is a computer program that's at the core of an operating system (OS):
The kernel is responsible for managing the OS's resources, including memory, disk
storage, and networking. It also:
Prevents and resolves conflicts between processes
Provides an interface for the rest of the OS to read and write files and communicate
on the network
Handles system calls from software applications
Controls processes
Handles interrupts
Facilitates input/output (I/O) operations
Network Management
The complexity of networks and services has created modern challenges for IT
professionals and users. Network management is a set of processes and procedures that
help organizations to optimize their computer networks. Mainly, it ensures that users have
the best possible experience while using network applications and services.
Network management is a fundamental concept of computer networks. Network
Management Systems is a software application that provides network administrators with
information on components in their networks. It ensures the quality of service and
availability of network resources. It also examines the operations of a network,
reconstructs its network configuration, modifies it for improving performance of tasks.
Security Management
The security mechanisms in an operating system ensure that authorized programs have
access to resources, and unauthorized programs have no access to restricted resources.
Security management refers to the various processes where the user changes the file,
memory, CPU, and other hardware resources that should have authorization from the
operating system.
I/O Device Management
The I/O device management component is an I/O manager that hides the details of
hardware devices and manages the main memory for devices using cache and spooling.
This component provides a buffer cache and general device driver code that allows the
system to manage the main memory and the hardware devices connected to it. It also
provides and manages custom drivers for particular hardware devices.
The purpose of the I/O system is to hide the details of hardware devices from the
application programmer. An I/O device management component allows highly efficient
resource utilization while minimizing errors and making programming easy on the entire
range of devices available in their systems.
Secondary Storage Management
Broadly, the secondary storage area is any space, where data is stored permanently and
the user can retrieve it easily. Your computer‟s hard drive is the primary location for your
files and programs. Other spaces, such as CD-ROM/DVD drives, flash memory cards, and
networked devices, also provide secondary storage for data on the computer. The
computer‟s main memory (RAM) is a volatile storage device in which all programs reside, it
provides only temporary storage space for performing tasks. Secondary storage refers to
the media devices other than RAM (e.g. CDs, DVDs, or hard disks) that provide additional
space for permanent storing of data and software programs which is also called non-
volatile storage.
Main Memory Management
Main memory is a flexible and volatile type of storage device. It is a large sequence of
bytes and addresses used to store volatile data. Main memory is also called Random
Access Memory (RAM), which is the fastest computer storage available on PCs. It is costly
and low in terms of storage as compared to secondary storage devices. Whenever
computer programs are executed, it is temporarily stored in the main memory for
execution. Later, the user can permanently store the data or program in the secondary
storage device.
System Programs
In the context of an operating system, system programs are nothing but special software
which gives us facility to manage and control the computer's hardware and resources. Also
provide a convenient environment for program development and execution.
According to computer hierarchy, one which comes at last is hardware. Then it is Operating
System, System Programs and finally Application Programs. Some of the System Programs
are simple user interfaces while others are complex. It traditionally lies between the user
interface and system calls so users can only view up-to-the System Programs and can‟t
see System Calls.
2. Command Line Interface (CLI’s) : CLIs is the essential tool for user . It provides user
facility to write commands directly to the system for performing any operation. It is a
text-based way to interact with operating system. CLIs can perform many tasks like file
manipulation, system configuration and etc.
3. Device drivers: Device drivers work as a simple translator for OS and devices.
Basically it act as an intermediatory between the OS and devices and provide facility to
both OS and devices to understand each other‟s language so that they can work
together efficiently without interrupt.
4. Status Information: Information like date, time amount of available memory, or disk
space is asked by some users. Others provide detailed performance, logging, and
debugging information which is more complex. All this information is formatted and
displayed on output devices or printed. Terminal or other output devices or files or a
window of GUI is used for showing the output of programs.
5. File Modification: This is used for modifying the content of files. Files stored on disks
or other storage devices, we use different types of editors. For searching contents of
files or perform transformations of files we use special commands.
7. Program Loading and Execution: When the program is ready after Assembling and
compilation, it must be loaded into memory for execution. A loader is part of an
operating system that is responsible for loading programs and libraries. It is one of the
essential stages for starting a program. Loaders, linkage editors, and Overlay loaders
are provided by the system.
8. Communications: Connections among processes, users, and computer systems are
provided by programs. Users can send messages to another user on their screen, User
can send e-mail, browsing on web pages, remote login, the transformation of files from
one user to another.
Process Management
Earlier there used to be only single-task performing systems. In this way, there used to be
only one process running at a time. And it had the freedom to utilise all the resources in the
system. But today, we have multitasking and multiprocessing operating systems, where
more than one process runs at a time.
This creates problems such as deadlock and multiple processes requesting for the same
resource, processor, or RAM space allocation to execute.
All these problems require a proper solution, and this instigates the operating system to
carry out processor management.
Process is important part of the operating system. It allows you to control the way your
computer runs by managing the currently active processes. This includes ending processes
that are no longer needed, setting process priorities, and more. You can do it on your
computer also.
There are a few ways to manage your processes. The first is through the use of Task
Manager. This allows you to see all of the processes currently running on your computer and
their current status and CPU/memory usage. You can end any process that you no longer
need, set a process priority, or start or stop a service.
The Role of the Operating System
The operating system is the backbone of a computer. It‟s responsible for managing all of
computer‟s processes and making it possible to interact with your device.
When you boot up your computer, the operating system is the first thing that starts running. It
loads into memory and starts managing all of the other programs and processes running on
your computer. It also controls files and devices, allocates system resources, and handles
communications between applications and users.
In short, the operating system is responsible for making sure that everything runs smoothly
on your computer.
What is a process?
A process is an active execution unit of a program that performs some action. An operating
system has the right to create, schedule, and terminate a process. There are four sections in
a process:
Text: holds the current activities represented by the value of Program Counter
Stack: holds temporary data such as local variables, functional parameters,
return addresses, etc.
Data: holds the global variables
Heap: dynamically allocated memory to process during runtime.
The operating system controls a process by a block called Process Control Block (PCB). It
is a type of Data Structure that is maintained by the OS for storing the context of each
process.
Process Attributes
Process Id: a unique identifier assigned by the operating system to each process.
Process State: there are a few possible states a process goes through during
execution.
CPU registers: stores the details of the process when it is swapped in and out of
the CPU, just like the program counter. Like the Program Counter (CPU registers
must be saved and restored when a process is swapped in and out of the CPU)
I/O status information: shows information like the device to which a process is
allotted and details of open files. For example, devices allocated to the process,
open files, etc
CPU scheduling information: processes are scheduled and executed based on
priority. For example, Priority (Different processes may have different priorities, for
example, a shorter process assigned high priority in the shortest job first
scheduling)
Accounting & Business information: information about the amount of CPU used
and time utilities like a job or process number, real-time utilised, etc.
Memory management information: information about the value of base registers
and limit registers, segment tables, and pages.
*********************************************************************************************************
In an operating system (OS), the base register is a key component of memory management
that holds the starting address of a process's memory segment. The base register is used to
protect memory space and control access in a system
In an operating system (OS), the limit register contains the maximum offset from zero that a
process can access. It's used in conjunction with the base register to check addresses
generated in user mode
In an operating system (OS), an offset is a value or position that can be adjusted to access
data or perform calculations in a specific location.
A segment table in an operating system (OS) is a data structure that tracks the different
memory segments used by a program:
Purpose: The segment table maps logical addresses generated by the CPU to physical
addresses in memory. It also helps the OS keep track of which parts of memory are being
used by each process and prevents conflicts between processes.
How it works: Each entry in the segment table corresponds to a program segment and
containsdetails about the segment's size and beginning address. When a program reads
memory, the CPU uses the segment entry value to find the relevant record in the segment
table.
Components:A segment table includes a segment base and a segment limit. The segment
base indicates the starting address of the segment in physical memory, while the segment limit
determines the size of the segment.
Storage:The segment table is stored in the main memory. However, in Linux, the segment
table is stored in a file on disk to save memory space and make it easier to move processes
between computers.
A logical address is a virtual address that a CPU generates while a program is running to
reference a memory location. It's also known as a virtual address because it doesn't
physically exist
********************************************************************************************************
Process priority is a numeric value that determines the order in which processes are
scheduled and executed by an operating system (OS). It's based on the importance or
urgency of each process.
Here are some things to know about process priority:
Priority value: The priority value ranges from 0 to 99, with 0 being the lowest priority and 99
being the highest.
Priority assignment: The priority is assigned when the Process Control Block (PCB) is
created. It can depend on factors like the process's age and the resources it consumes.
Scheduling: The kernel uses the priority to schedule processes, giving more CPU time to
higher-priority tasks.
Monitoring: You can check a process's priority using the automatic display mode (ADM)
screen or Operations Centre. You can also use the MX (Mix Entries) command to display
processes and their priorities.
Changing priority: You can change a process's priority using the PR (Priority) system
command.
All of the above attributes of a process are also known as the context of the process.
Every process has its own process control block(PCB), i.e. each process will have a
unique PCB. All of the above attributes are part of the PCB.
Process Operations
Process operations in an operating system refer to the various activities the OS performs
to manage processes. These operations include process creation, process scheduling,
execution and killing the process. Here are the key process operations:
Pointer: It is a stack pointer that is required to be saved when the process is switched
from one state to another to retain the current position of the process.
Process state: It stores the respective state of the process.
Process number: Every process is assigned a unique id known as process ID or PID
which stores the process identifier.
Program Counter (PC):Program Counter stores the counter, which contains the
address of the next instruction that is to be executed for the process.
A program counter (PC) is a register in a computer's central processing unit (CPU) that keeps track of
the memory address of the next instruction to be executed:
What it does: Tracks the memory address of the next instruction to be executed
How it works: The CPU reads the address from the PC and executes the instruction in sequence
What happens when it increments: The address specified by the PC is incremented by +n, where
+1 is for a 1-word instruction and +2 is for a 2-word instruction
What happens when it encounters a jump or branch instruction: The PC is loaded with a new
address, altering the sequence of execution
What happens if it points to an invalid address: The program may crash or an error may occur
The PC is also known as the instruction pointer.
Register: Registers in the PCB, it is a data structure. When a processes is running and
it‟s time slice expires, the current value of process specific registers would be stored in
the PCB and the process would be swapped out. When the process is scheduled to be
run, the register values is read from the PCB and written to the CPU registers. This is
the main purpose of the registers in the PCB.
Memory limits: This field contains the information about memory management
system used by the operating system. This may include page tables, segment tables,
etc.
List of Open files: This information includes the list of files opened for a process.
Process States
As a process executes, it changes state. The state of a process is defined in part by the
current activity of that process. Each process may be one of the following states:
New: This state represents a newly created process that hasn‟t started running yet. It has
not been loaded into the main memory, but its process control block (PCB) has been
created, which holds important information about the process.
Ready: A process in this state is ready to run as soon as the CPU becomes available. It is
waiting for the operating system to give it a chance to execute.
Running: This state means the process is currently being executed by the CPU. Since
we‟re assuming there is only one CPU, at any time, only one process can be in this state.
Blocked/Waiting: This state means the process cannot continue executing right now. It is
waiting for some event to happen, like the completion of an input/output operation (for
example, reading data from a disk).
Exit/Terminate: A process in this state has finished its execution or has been stopped by
the user for some reason. At this point, it is released by the operating system and removed
from memory.
Process Scheduling
The process scheduling is the activity of the process manager that handles the removal of
the running process from the CPU and the selection of another process on the basis of a
particular strategy.
Process scheduling is essential part of a Multiprogramming operating systems. Such
operating systems allow more than one process to be loaded into the executable memory at
a time and the loaded process shares the CPU using time multiplexing.
Categories of Scheduling
There are two categories of scheduling:
Non-preemptive: Here the resource can‟t be taken from a process until the process
completes execution. The switching of resources occurs when the running process
terminates and moves to a waiting state.
Preemptive: Here the OS allocates the resources to a process for a fixed amount of
time. During resource allocation, the process switches from running state to ready
state or from waiting state to ready state. This switching occurs as the CPU may give
priority to other processes and replace the process with higher priority with the
running process.
The OS can use different policies to manage each queue (FIFO, Round Robin, Priority, etc.).
The OS scheduler determines how to move processes between the ready and run queues
which can only have one entry per processor core on the system; in the above diagram, it
has been merged with the CPU.
Schedulers: Schedulers are special system software which handle process scheduling in
various ways. Their main task is to select the jobs to be submitted into the system and to
decide which process to run. Schedulers are of three types.
Long-Term Scheduler
Short-Term Scheduler
Medium-Term Scheduler
Long-term schedulers are in charge of determining the order in which processes are
executed and managing the execution of processes that may take a long time to complete,
such as batch jobs or background tasks.
A long-term scheduler‟s primary function is to minimize processing time by taking the
mixtures of CPU-bound jobs and I/O-bound jobs.
[Link]
Short Term Scheduler: It is also called as CPU scheduler. Its main objective is to increase
system performance in accordance with the chosen set of criteria. It is the change of ready
state to running state of the process. CPU scheduler selects a process among the processes
that are ready to execute and allocates CPU to one of them.
Short-term schedulers, also known as dispatchers, make the decision of which process to
execute next. Short-term schedulers are faster than long-term schedulers.
Independent process: A process that cannot be affected by other processes, and does
not affect them either. Independent processes do not share data with other processes
or systems. Independent Processes are those processes whose task is not dependent
on any other processes. An independent process is not affected by the execution of
other processes
Cooperating process: A process that can affect or be affected by other
processes. Cooperating processes share data with other processes and systems.
Cooperating Processes are those processes that depend on other processes or
processes. They work together to achieve a common task in an operating system.
These processes interact with each other by sharing the resources such as CPU,
memory, and I/O devices to complete the task. Co-operating process can be affected by
other executing processes. in reality, there are many situations when cooperative nature
can be utilized for increasing computational speed, convenience, and modularity.
Inter process communication needed in Cooperating Processes.
There are several reasons for providing an environment that allows process cooperation
Information sharing: Several users may be interested in a single piece of information.
Example: Shared file
Information can be shared concurrently.
Computational Speed up: In order to achieve Computational Speed if we having a task,
divide the task into several subtasks and all these subtasks to make run concurrently in that
way we can speed up the system, instead of taking one task waiting for it complete from
beginning to till end. We can break the task into several subtasks and all the subtasks will
be made to run concurrently and hence can achieve more speed in our system. When we
do that when tasks are broken down into several different tasks they are assigned to several
different processes. Since all these processes are belong to one single task or one main
task those processes need to communicate each other.
Modularity: We want to design the system by dividing into seperate modules. Later these
modules put together to achieve a single goal.
Convenience: If we allow the processes to cooperate with other that become very
convenient for user.
User may be use different tasks at the same time. Different processes are running at the
same time.
Cooperting processes require an IPC mechanism that will allow them to exchange data and
information. There are two fundamental models of interprocess communication.
Shared memory model
Message passing model
In shared memory model, a region of memory that is shared by cooperting processes is
established. Portion of memory shared by all the processes cooperting each other.
Processes can then exchange information by reading and writing data to the shared region.
Whenever one process wants communicate with another it will do is write the information or
the thing that want to share or communicate to the other processes into that shared memory
region and the other processes can read that data that was written by first process from the
shared memory region and then it will understand what it actually try to communicate.
Suppose process A wants to communicate with process B and needs to attach it is address space to
this shared memory segment. Process A will write a message to the shared memory, and Process B
will read that message from the shared memory. So, processes are responsible for ensuring
synchronization so that both processes do not write to the same location at the same time.
Message Passing: Another important way inter-process communication occurs with other
processes is via message passing. When two or more processes participate in inter-process
communication, each process sends messages to the others via Kernel. Here is an example
of sending messages between two processes: – Here, the process sends a message like
“M” to the OS kernel. This message is then read by Process B. A communication link is
required between the two processes for successful message exchange. There are several
ways to create these links.
Message passing: in the message passing model communication takes place by means of
messages exchanged between the cooperting processes.
The processes communicate with each other by exchanging messages. For this purpose,
a Communication Link must exist between the processes and it must facilitate at least two
operations send (message) and receive (message). The size of messages may be variable
or fixed.
The critical section is a code segment where the shared variables can be accessed. An
atomic action is required in a critical section i.e. only one process can execute in its critical
section at a time. All the other processes have to wait to execute in their critical sections.
In the above diagram, the entry section handles the entry into the critical section. It acquires
the resources needed for execution by the process. The exit section handles the exit from
the critical section. It releases the resources and also informs the other processes that the
critical section is free.
S--;
}
Signal: The signal operation increments the value of its argument S. A signal operation on a
semaphore activates a process blocked on the semaphore if any, or increments the value
of the semaphore by 1. Due to these semantics, semaphores are also called counting
semaphores. The initial value of a semaphore determines how many processes can get
past the wait operation.
signal(S)
{
S++;
}
Types of Semaphores
There are two main types of semaphores i.e. counting semaphores and binary semaphores.
Counting Semaphores: These are integer value semaphores and have an
unrestricted value domain. These semaphores are used to coordinate the resource
access, where the semaphore count is the number of available resources. If the
resources are added, semaphore count automatically incremented and if the
resources are removed, the count is decremented.
Binary Semaphores: The binary semaphores are like counting semaphores but their
value is restricted to 0 and 1. The wait operation only works when the semaphore is 1
and the signal operation succeeds when semaphore is 0. It is sometimes easier to
implement binary semaphores than counting semaphores.
Difference between Counting and Binary Semaphores
Criteria Binary Semaphore Counting Semaphore
A counting semaphore is a
A Binary Semaphore is a
semaphore that has multiple values of
semaphore whose integer
the counter. The value can range over
value range over 0 and 1.
an unrestricted domain.
typedef struct {
int semaphore_variable;
typedef struct {
Structure Queue
Implementation
int semaphore_variable;
list; //A
}binary_semaphore;
queue to store the list of task
}counting_semaphore;
0 means that a process or a
thread is accessing the
The value can range from 0 to N,
critical section, other
where N is the number of process or
Representation process should wait for it to
thread that has to enter the critical
exit the critical section. 1
section.
represents the critical
section is free.
Yes, it guarantees mutual No, it doesn‟t guarantees mutual
exclusion, since just one exclusion, since more than one
Mutual Exclusion
process or thread can enter process or thread can enter the critical
the critical section at a time. section at a time.
No, it doesn‟t guarantees
bounded wait, as only one Yes, it guarantees bounded wait,
process can enter the critical since it maintains a list of all the
section, and there is no limit process or threads, using a queue,
Bounded wait
on how long the process can and each process or thread get a
exist in the critical section, chance to enter the critical section
making another process to once. So no question of starvation.
starve.
No waiting queue is present
then FCFS (first come first Waiting queue is present then FCFS
Starvation serve) is not followed (first come first serve) is followed
so,starvation is possible and so,no starvation hence no busy wait.
busy wait present
Used only for a single
Used for any number of instance of
Number of instance of resource type
instance
resource of type [Link] can be used for
[Link] can be usedonly for 2
any number of processes.
processes.
Operating System Handout
Preemptive Scheduling:
Preemptive scheduling is used when a process switches from running state to ready
state or from waiting state to ready state.
The resources (mainly CPU cycles) are allocated to the process for the limited amount
of time and then is taken away, and the process is again placed back in the ready queue
if that process still has CPU burst time remaining.
That process stays in ready queue till it gets next chance to execute.
Non-Preemptive Scheduling:
Non-preemptive Scheduling is used when a process terminates, or a process switches
from running to waiting state.
In this scheduling, once the resources (CPU cycles) is allocated to a process, the process
holds the CPU till it gets terminated or it reaches a waiting state.
In case of non-preemptive scheduling does not interrupt a process running CPU in
middle of the execution.
Instead, it waits till the process complete its CPU burst time and then it can allocate the
CPU to another process.
Basis for
Preemptive Scheduling Non Preemptive Scheduling
Comparison
Once resources are allocated to a
The resources are allocated to a process, the process holds it till it
Basic
process for a limited time. completes its burst time or switches to
waiting state.
Process can be interrupted in Process can not be interrupted till it
Interrupt
between. terminates or switches to waiting state.
If a high priority process
If a process with long burst time is
frequently arrives in the ready
Starvation running CPU, then another process with
queue, low priority process may
less CPU burst time may starve.
starve.
Preemptive scheduling has
Non-preemptive scheduling does not
Overhead overheads of scheduling the
have overheads.
processes.
Flexibility Preemptive scheduling is flexible. Non-preemptive scheduling is rigid.
Preemptive scheduling is cost Non-preemptive scheduling is not cost
Cost
associated. associative.
Scheduling Criteria
There are several different criteria to consider when trying to select the "best"
scheduling algorithm for a particular situation and environment, including:
o CPU utilization - Ideally the CPU would be busy 100% of the time, so
as to waste 0 CPU cycles. On a real system CPU usage should range from
40% ( lightly loaded ) to 90% ( heavily loaded. )
o Throughput - Number of processes completed per unit time. May range
from 10 / second to 1 / hour depending on the specific processes.
In brief:
Arrival Time: Time at which the process arrives in the ready queue.
Completion Time: Time at which process completes its execution.
Burst Time: Time required by a process for CPU execution.
Turn Around Time: Time Difference between completion time and arrival time.
Turn Around Time = Completion Time – Arrival Time
Waiting Time(W.T): Time Difference between turnaround time and burst time.
Waiting Time = Turn Around Time – Burst Time
Advantages-
It is simple and easy to understand.
It can be easily implemented using queue data structure.
It does not lead to starvation.
Disadvantages-
It does not consider the priority or burst time of the processes.
It suffers from convoy effect i.e. processes with higher burst time arrived before
the processes with smaller burst time.
Example 1:
Example 2:
Consider the processes P1, P2, P3 given in the below table, arrives for execution in
the same order, with Arrival Time 0, and given Burst Time,
PROCESS ARRIVAL TIME BURST TIME
P1 0 24
P2 0 3
P3 0 3
Gantt chart
P1 P2 P3
0 24 27 30
Average Waiting Time = (Total Wait Time) / (Total number of processes) = 51/3 = 17 ms
Average Turn Around time = (Total Turn Around Time) / (Total number of processes)
= 81 / 3 = 27 ms
Throughput = 3 jobs/30 sec = 0.1 jobs/sec
Example 3:
Consider the processes P1, P2, P3, P4 given in the below table, arrives for execution
in the same order, with given Arrival Time and Burst Time.
PROCESS ARRIVAL TIME BURST TIME
P1 0 8
P2 1 4
P3 2 9
P4 3 5
Gantt chart
P1 P2 P3 P4
0 8 12 21 26
Average Waiting Time = (Total Wait Time) / (Total number of processes)= 35/4 = 8.75 ms
Average Turn Around time = (Total Turn Around Time) / (Total number of processes)
61/4 = 15.25 ms
Advantages-
SRTF is optimal and guarantees the minimum average waiting time.
It provides a standard for other algorithms since no other algorithm performs
better than it.
Disadvantages-
It can not be implemented practically since burst time of the processes can not
be known in advance.
It leads to starvation for processes with larger burst time.
Priorities can not be set for the processes.
Processes with larger burst time have poor response time.
Example-01:
Consider the set of 5 processes whose arrival time and burst time are given below-
Process Id Arrival time Burst time
P1 3 1
P2 1 4
P3 4 2
P4 0 6
P5 2 3
Solution-
If the CPU scheduling policy is SJF non-preemptive, calculate the average waiting
time and average turnaround time.
Gantt Chart-
Now, we know-
Turn Around time = Exit time – Arrival time
Waiting time = Turn Around time – Burst time
Example-02:
Consider the set of 5 processes whose arrival time and burst time are given below-
Process Id Arrival time Burst time
P1 3 1
P2 1 4
P3 4 2
P4 0 6
P5 2 3
If the CPU scheduling policy is SJF pre-emptive, calculate the average waiting time and
average turnaround time.
Solution-
Gantt Chart-
Now,
Example-03:
Consider the set of 6 processes whose arrival time and burst time are given below-
If the CPU scheduling policy is shortest remaining time first, calculate the average
waiting time and average turnaround time.
Solution-
Gantt Chart-
Now, we know-
Turn Around time = Exit time – Arrival time
Waiting time = Turn Around time – Burst time
Now,
Average Turn Around time = (19 + 12 + 4 + 1 + 5 + 2) / 6 = 43 / 6 = 7.17 unit
Average waiting time = (12 + 7 + 1 + 0 + 3 + 1) / 6 = 24 / 6 = 4 unit
Example -04:
Consider the set of 3 processes whose arrival time and burst time are given below-
If the CPU scheduling policy is SRTF, calculate the average waiting time and average
turn around time.
Solution-
Gantt Chart-
Now, we know-
Turn Around time = Exit time – Arrival time
Waiting time = Turn Around time – Burst time
Now,
Average Turn Around time = (13 + 4 + 20) / 3 = 37 / 3 = 12.33 unit
Average waiting time = (4 + 0 + 11) / 3 = 15 / 3 = 5 unit
Example-05:
Consider the set of 4 processes whose arrival time and burst time are given below-
If the CPU scheduling policy is SRTF, calculate the waiting time of process P2.
Solution-
Gantt Chart-
Now, we know-
Turn Around time = Exit time – Arrival time
Waiting time = Turn Around time – Burst time
Thus,
Turn Around Time of process P2 = 55 – 15 = 40 unit
Waiting time of process P2 = 40 – 25 = 15 unit
Advantages-
Disadvantages-
It leads to starvation for processes with larger burst time as they have to repeat
the cycle many times.
Its performance heavily depends on time quantum.
Priorities can not be set for the processes.
Thus, higher value of time quantum is better in terms of number of context switch.
Example-01:
Consider the set of 5 processes whose arrival time and burst time are given below-
If the CPU scheduling policy is Round Robin with time quantum = 2 unit, calculate
the average waiting time and average turnaround time.
Solution-
Ready Queue- P5, P1, P2, P5, P4, P1, P3, P2, P1
Gantt Chart-
Now, we know-
Turn Around time = Exit time – Arrival time
Waiting time = Turn Around time – Burst time
Process Id Exit time Turn Around time Waiting time
P1 13 13 – 0 = 13 13 – 5 = 8
P2 12 12 – 1 = 11 11 – 3 = 8
P3 5 5–2=3 3–1=2
P4 9 9–3=6 6–2=4
P5 14 14 – 4 = 10 10 – 3 = 7
Now,
Average Turn Around time = (13 + 11 + 3 + 6 + 10) / 5 = 43 / 5 = 8.6 unit
Average waiting time = (8 + 8 + 2 + 4 + 7) / 5 = 29 / 5 = 5.8 unit
Problem-02:
Consider the set of 6 processes whose arrival time and burst time are given below-
Process Id Arrival time Burst time
P1 0 4
P2 1 5
P3 2 2
P4 3 1
P5 4 6
P6 6 3
If the CPU scheduling policy is Round Robin with time quantum = 2, calculate the average
waiting time and average turnaround time.
Solution-
Ready Queue- P5, P6, P2, P5, P6, P2, P5, P4, P1, P3, P2, P1
Gantt chart-
Now, we know-
Turn Around time = Exit time – Arrival time
Waiting time = Turn Around time – Burst time
Now, we know-
Turn Around time = Exit time – Arrival time
Waiting time = Turn Around time – Burst time
Process Id Exit time Turn Around time Waiting time
P1 32 32 – 5 = 27 27 – 5 = 22
P2 27 27 – 4 = 23 23 – 6 = 17
P3 33 33 – 3 = 30 30 – 7 = 23
P4 30 30 – 1 = 29 29 – 9 = 20
P5 6 6–2=4 4–2=2
P6 21 21 – 6 = 15 15 – 3 = 12
Now,
The waiting time for the process having the highest priority will always be zero in
preemptive mode.
The waiting time for the process having the highest priority may not be zero in non-
preemptive mode.
Priority scheduling in preemptive and non-preemptive mode behaves exactly same under
following conditions-
The arrival time of all the processes is same
All the processes become available
Advantages-
It considers the priority of the processes and allows the important processes to
run first.
Priority scheduling in pre-emptive mode is best suited for real time operating
system.
Disadvantages-
Processes with lesser priority may starve for CPU.
There is no idea of response time and waiting time.
Problem-01:
Consider the set of 5 processes whose arrival time and burst time are given below-
Process Id Arrival time Burst time Priority
P1 0 4 2
P2 1 3 3
P3 2 1 4
P4 3 5 5
P5 4 2 5
If the CPU scheduling policy is priority non-preemptive, calculate the average waiting time
and average turnaround time. (Higher number represents higher priority)
Solution-
Gantt Chart-
Now, we know-
Turn Around time = Exit time – Arrival time
Waiting time = Turn Around time – Burst time
Process Id Exit time Turn Around time Waiting time
P1 4 4–0=4 4–4=0
P2 15 15 – 1 = 14 14 – 3 = 11
P3 12 12 – 2 = 10 10 – 1 = 9
P4 9 9–3=6 6–5=1
P5 11 11 – 4 = 7 7–2=5
Now,
Average Turn Around time = (4 + 14 + 10 + 6 + 7) / 5 = 41 / 5 = 8.2 unit
Average waiting time = (0 + 11 + 9 + 1 + 5) / 5 = 26 / 5 = 5.2 unit
Problem-02: Consider the set of 5 processes whose arrival time and burst time are
given below-
Process Id Arrival time Burst time Priority
P1 0 4 2
P2 1 3 3
P3 2 1 4
P4 3 5 5
P5 4 2 5
If the CPU scheduling policy is priority preemptive, calculate the average waiting
time and average turn around time. (Higher number represents higher priority).
Solution-
Gantt Chart-
Now, we know-
Turn Around time = Exit time – Arrival time
Waiting time = Turn Around time – Burst time
Process Id Exit time Turn Around time Waiting time
P1 15 15 – 0 = 15 15 – 4 = 11
P2 12 12 – 1 = 11 11 – 3 = 8
P3 3 3–2=1 1–1=0
P4 8 8–3=5 5–5=0
P5 10 10 – 4 = 6 6–2=4
Now,
Average Turn Around time = (15 + 11 + 1 + 5 + 6) / 5 = 38 / 5 = 7.6 unit
Average waiting time = (11 + 8 + 0 + 0 + 4) / 5 = 23 / 5 = 4.6 unit
4.3 Deadlock
Deadlock is a situation where a set of processes are blocked because each process is
holding a resource and waiting for another resource acquired by some other process.
For example, in the below diagram, Process 1 is holding Resource 1 and waiting for
resource 2 which is acquired by process 2, and process 2 is waiting for resource 1.
The requested resource is blocked by the other The requested resource is continuously be
4
process. used by the higher priority processes.
Deadlock Handling
The various strategies for handling deadlock are-
1. Deadlock Prevention
2. Deadlock Avoidance
3. Deadlock Detection and Recovery
4. Deadlock Ignorance
1. Deadlock Prevention
Deadlocks can be prevented by preventing at least one of the four required
conditions:
Mutual Exclusion
Shared resources such as read-only files do not lead to deadlocks.
Unfortunately, some resources, such as printers and tape drives, require exclusive
access by a single process.
Hold and Wait
To prevent this condition processes must be prevented from holding one or more
resources while simultaneously waiting for one or more others.
No Preemption
Preemption of process resource allocations can prevent this condition of deadlocks,
when it is possible.
Circular Wait
One way to avoid circular wait is to number all resources, and to require that processes
request resources only in strictly increasing ( or decreasing ) order.
2. Deadlock Avoidance
In deadlock avoidance, the operating system checks whether the system is in safe state
or in unsafe state at every step which the operating system performs.
The process continues until the system is in safe state.
Once the system moves to unsafe state, the OS has to backtrack one step.
In simple words, The OS reviews each allocation so that the allocation doesn't cause
the deadlock in the system.
4. Deadlock Ignorance
This strategy involves ignoring the concept of deadlock and assuming as if it does not
exist.
This strategy helps to avoid the extra overhead of handling deadlock.
Windows and Linux use this strategy and it is the most widely used method.
2. Use: The process can operate on the resource (for example, if the
resource is a printer, the process can print on the printer).
Consider an example when two trains are coming toward each other
on the same track and there is only one track, none of the trains can
move once they are in front of each other. A similar situation occurs in
operating systems when there are two or more processes that hold
some resources and wait for resources held by other(s). For example,
in the below diagram, Process 1 is holding Resource 1 and waiting for
resource 2 which is acquired by process 2, and process 2 is waiting for
resource 1.
Deadlock System Model − The Deadlock System model is a way to
describe and analyze systems that may be prone to deadlocks, which
occur when two or more processes are unable to proceed because they
are each waiting for the other to release a resource. Below are the
components of this model −
Resources − The system has a set of resources that are shared
among processes. These resources can be hardware or software
components, such as memory, files, printers, or network
connections. Each resource is identified by a unique name or
identifier.
Processes − The system has a set of processes that request and
release resources. Processes are units of execution that can be
started, suspended, resumed, and terminated. Each process is
identified by a unique process ID.
Resource Allocation − Each resource can be in one of two states ,
allocated or available. A resource that is allocated to a process
cannot be used by any other process until it is released.
Request and Release − A process can request a resource by
sending a request to the system. If the resource is available, it will
be allocated to the process. When a process is finished using a
resource, it must release it so that it can be used by other processes.
Resource Dependency − Some processes may require multiple
resources to complete their tasks. A resource dependency graph
can be used to represent the relationships between processes and
resources and to detect potential deadlocks.
Deadlock Detection − A deadlock can occur when two or more
processes are waiting for resources that are being held by other
processes, creating a circular dependency. Deadlock
detection algorithms can be used to detect when a deadlock has
occurred, so that corrective action can be taken.
Deadlock Resolution − Once a deadlock has been detected, it can
be resolved by breaking the circular dependency between the
processes. This can be done by releasing one or more resources that
are being held by a process, or by preempting one or more
processes that are holding resources. The Working of some of the
techniques are given below –
o Resource preemption is a technique used to break the
circular wait condition of a deadlock. The operating system
can preempt resources from one or more processes involved
in the deadlock and allocate them to the processes that need
them. Preemption can be done either selectively or globally.
In selective preemption, only the resources that are required
to resolve the deadlock are preempted, while in global
preemption, all the resources held by the deadlocked
processes are preempted.
o When a process is terminated, all the resources held by
the process are released, and other processes can proceed.
However, this approach can lead to data loss and
inconsistency if the terminated process was in the middle of a
critical task.
Deadlock Avoidance − Deadlock avoidance is a technique used
to prevent the occurrence of deadlocks in a computer system. The
goal of deadlock avoidance is to ensure that all resources required
by a process are available before the process starts execution,
thereby avoiding the possibility of deadlock.
Difference between Starvation and Deadlock
Sr. Deadlock Starvation
1 Deadlock is a situation where no process got Starvation is a situation where the low
blocked and no process proceeds priority process got blocked and the high
priority processes proceed.
5 Deadlock happens when Mutual exclusion, It occurs due to the uncontrolled priority
hold and wait, No preemption and circular and resource management.
wait occurs simultaneously.
Deadlocks characterization:
Necessary conditions for Deadlocks:
Deadlock can arise if the following four conditions hold
simultaneously (Necessary Conditions)
1. Mutual Exclusion
A resource can only be shared in mutually exclusive manner. It
implies, if two processes cannot use the same resource at the same
time.
2. Hold and Wait
A process waits for some resources while holding another resource
at the same time.
3. No preemption
The process which once scheduled will be executed till the
completion. No other process can be scheduled by the scheduler
meanwhile.
4. Circular Wait
All the processes must be waiting for the resources in a cyclic
manner so that the last process is waiting for the resource which is
being held by the first process.
methods for handling Deadlock
1. Deadlock prevention:
Deadlock happens only when Mutual Exclusion, hold and wait, No
preemption and circular wait holds simultaneously. If it is possible to
violate one of the four conditions at any time then the deadlock can
never occur in the system.
The idea behind the approach is very simple that we have to fail one of
the four conditions but there can be a big argument on its physical
implementation in the system.
2. Deadlock avoidance:
In deadlock avoidance, the operating system checks whether the
system is in safe state or in unsafe state at every step which the operating
system performs. The process continues until the system is in safe state.
Once the system moves to unsafe state, the OS has to backtrack one step.
In simple words, The OS reviews each allocation so that the allocation
doesn't cause the deadlock in the system.
3. Deadlock detection and recovery:
This approach let the processes fall in deadlock and then periodically
check whether deadlock occur in the system or not. If it occurs then it
applies some of the recovery methods to the system to get rid of
deadlock.
Resource-Allocation Graph
The resource allocation graph is the pictorial representation of the state
of a system. As its name suggests, the resource allocation graph is the
complete information about all the processes which are holding some
resources or waiting for some resources.
It also contains the information about all the instances of all the
resources whether they are available or being used by the processes.
In Resource allocation graph, the process is represented by a Circle
while the Resource is represented by a rectangle.
Example:
Let's consider 3 processes P1, P2 and P3, and two types of resources R1
and R2. The resources are having 1 instance each.
The graph is deadlock free since no cycle is being formed in the graph
If we analyze the graph then we can find out that there is a cycle formed
in the graph since the system is satisfying all the four conditions of
deadlock.
Deadlock Prevention
Deadlock prevention is a technique used in operating systems to ensure
that deadlocks, which are situations where two or more processes are
unable to proceed because each is waiting for the other to release a
resource, do not occur. It involves designing the system in such a way
that at least one of the necessary conditions for deadlock cannot hold.
This typically requires careful resource allocation and tracking, as well
as enforcing certain rules and protocols to prevent deadlock formation.
Deadlock Characteristics
The deadlock has the following characteristics:
1. Mutual Exclusion
2. Hold and Wait
3. No preemption
4. Circular wait
We can prevent a Deadlock by eliminating any of the above four
conditions.
Eliminate Mutual Exclusion: It is not possible to dis-satisfy
the mutual exclusion because some resources, such as the tape drive
and printer, are inherently non-shareable.
Eliminate Hold and wait: Allocate all required resources to the
process before the start of its execution, this way hold and wait
condition is eliminated but it will lead to low device utilization. for
example, if a process requires a printer at a later time and we have
allocated a printer before the start of its execution printer will remain
blocked till it has completed its execution. The process will make a new
request for resources after releasing the current set of resources. This
solution may lead to starvation.
In order to avoid deadlocks, the process must tell OS, the maximum
number of resources a process can request to complete its execution.
The simplest and most useful approach states that the process should
declare the maximum number of resources of each type it may ever
need. The Deadlock avoidance algorithm examines the resource
allocations so that there can never be a circular wait condition.
A 3 0 2 2
B 0 0 1 1
C 1 1 1 0
D 2 1 4 0
A 1 1 0 0
B 0 1 1 2
C 1 2 1 0
D 2 1 1 2
1. E = (7 6 8 4)
2. P = (6 2 8 3)
3. A = (1 4 0 1)
Above tables and vector E, P and A describes the resource allocation
state of a system. There are 4 processes and 4 types of the resources in a
system. Table 1 shows the instances of each resource assigned to each
process.
Table 2 shows the instances of the resources, each process still needs.
Vector E is the representation of total instances of each resource in the
system.
A state of the system is called safe if the system can allocate all the
resources requested by all the processes without entering into deadlock.
If the system cannot fulfill the request of all processes then the state of
the system is called unsafe.
Deadlock Detection
Deadlock Detection in OS, with this type of deadlock, multiple
processes try to acquire resources simultaneously but fail due to
insufficient resources at any given time. To avoid such problems, an OS
must periodically check the acquisition of resources by processes and
release any locked resources if necessary.
Algorithm:
Step 1: Take the first process (Pi) from the resource allocation graph
and check the path in which it is acquiring resource (Ri), and start a
wait-for-graph with that particular process.
Step 2: Make a path for the Wait-for-Graph in which there will be no
Resource included from the current process (P i) to next process (Pj),
from that next process (Pj) find a resource (Rj) that will be acquired by
next Process (Pk) which is released from Process (Pj).
Step 3: Repeat Step 2 for all the processes.
Step 4: After completion of all processes, if we find a closed-loop
cycle then the system is in a deadlock state, and deadlock is detected.
Now we will see the working of this Algorithm with an Example.
Consider a Resource Allocation Graph with 4 Processes P1, P2, P3, P4,
and 4 Resources R1, R2, R3, R4.
Find if there is a deadlock in the Graph using the Wait for Graph-based
deadlock detection algorithm.
Step 1: First take Process P1 which is waiting for Resource R1,
resource R1 is acquired by Process P2, Start a Wait-for-Graph for the
above Resource Allocation Graph.
Banker's Algorithm:
It is a banker algorithm used to avoid deadlock and allocate
resources safely to each process in the computer system. The 'S-
State' examines all possible tests or activities before deciding whether
the allocation should be allowed to each process. It also helps the
operating system to successfully share the resources between all the
processes. The banker's algorithm is named because it checks whether a
person should be sanctioned a loan amount or not to help the bank
system safely simulate allocation resources. In this section, we will learn
the Banker's Algorithm in detail. Also, we will solve problems based
on the Banker's Algorithm.
1. How much each process can request for each resource in the
system. It is denoted by the [MAX] request.
2. How much each process is currently holding each resource in a
system. It is denoted by the [ALLOCATED] resource.
3. It represents the number of each resource currently available in the
system. It is denoted by the [AVAILABLE] resource.
Following are the important data structures terms applied in the banker's
algorithm as follows:
Need[i][j]=max[i][j]-Allocation[i][j].
1. There are two vectors Wok and Finish of length m and n in a safety
algorithm.
2. Check the availability status for each type of resources [i], such as:
Need[i]<=Work
Finish[i]==false
If the i does not exist, go to step 4.
Finish[i] = true
4. If Finish[i] == true; it means that the system is safe for all processes.
Resource Request Algorithm
Let create a resource request array R[i] for each process P[i]. If the
Resource Request [j] equal to 'K', which means the process P[i] requires
'k' instances of Resources type R[j] in the system.
1. When the number of requested resources of each type is less than
the Need resources, go to step 2 and if the condition fails, which means
that the process P[i] exceeds its maximum claim for the resource. As the
expression suggests:
IfRequest(i)<=Need
Go to step 2;
2. And when the number of requested resources of each type is less than
the available resource for each process, go to step (3). As the expression
suggests:
IfRequest(i)<=Available
Else Process P[i] must wait for the resource since it is not available for
use.
Available=Available-Request
Allocation(i)=Allocation(i)+Request(i)
Needi = Needi - Requesti
When the resource allocation state is safe, its resources are allocated to
the process P(i). And if the new state is unsafe, the Process P (i) has to
wait for each type of Request R(i) and restore the old resource-allocation
state.
Example: Consider a system that contains five processes P1, P2, P3, P4,
P5 and the three resource types A, B and C. Following are the resources
types: A has 10, B has 5 and the resource type C has 7 instances.
P1 0 1 0 7 5 3 3 3 2
P2 2 0 0 3 2 2
P3 3 0 2 9 0 2
P4 2 1 1 2 2 2
P5 0 0 2 4 3 3
Need[i]=Max[i]-Allocation[i]
Need for P1: (7, 5, 3) - (0, 1, 0) = 7, 4, 3
Need for P2: (3, 2, 2) - (2, 0, 0) = 1, 2, 2
Need for P3: (9, 0, 2) - (3, 0, 2) = 6, 0, 0
Need for P4: (2, 2, 2) - (2, 1, 1) = 0, 1, 1
Need for P5: (4, 3, 3) - (0, 0, 2) = 4, 3, 1
Process Need
A B C
P1 7 4 3
P2 1 2 2
P3 6 0 0
P4 0 1 1
P5 4 3 1
Hence, we created the context of need matrix.
5, 3, 2 + 2, 1, 1 => 7, 4, 3
7, 4, 3 + 0, 0, 2 => 7, 4, 5
7, 4, 5 + 0, 1, 0 => 7, 5, 5
7, 5, 5 + 3, 0, 2 => 10, 5, 7
Hence, we execute the banker's algorithm to find the safe state and
the safe sequence like P2, P4, P5, P1 and P3.
Ans. 3: For granting the Request (1, 0, 2), first we have to check
that Request <= Available, that is (1, 0, 2) <= (3, 3, 2), since the
condition is true. So the process P1 gets the request immediately.
Deadlock Recovery :
A traditional operating system such as Windows doesn’t deal with
deadlock recovery as it is a time and space-consuming process. Real-
time operating systems use Deadlock recovery.
Process Termination
To eliminate the deadlock, we can simply kill one or more processes.
For this, we use two methods:
1. Abort all the Deadlocked Processes: Aborting all the processes
will certainly break the deadlock but at a great expense. The
deadlocked processes may have been computed for a long time and
the result of those partial computations must be discarded and there
is a probability to recalculate them later.
Resource Preemption
To eliminate deadlocks using resource preemption, we preempt some
resources from processes and give those resources to other processes.
This method will raise three issues –
1. Selecting a victim: We must determine which resources and which
processes are to be preempted and also order to minimize the cost.
2. Rollback: We must determine what should be done with the process
from which resources are preempted. One simple idea is total
rollback. That means aborting the process and restarting it.
functions
MemoTmanaqements the funclional:
a antoswhab handles07managcs
primar bomemnctsorplog
ocation i°isallo
etheo caledto
Some prbes
1t decidesubichprocesswiltqt nemory
at whatatime
33001
BasicHadwaTe into
Rotothe
ibutlts
Maiosmemovy the eqista
&
itsf
processo are thedeuice
only storage
that can acgs directly
Thattake
There are machbiocinstructions
mtmory adde SSeg as anqumertsbutthy
( StcondaU
will not takr disk addresScs
memory Throre anyiostructons %
Euccatiorn
&
must be
tngtueb'on
Tfthedalais not o
imatn
anudata beinguscd
of the
he maio memor
memoTythy
the CPO Cao oper
must be movecd there btfore
onthem to protect
hasi
hotCortoperation
Ensure
he os om àccessinq b ustI
o proccSS &
hddtion
otePo usY prucess
to protecttht frorm
must beprouid
Ont a00ther Thiçihoprolection
by theHtardwaTe.
> has
Cacb process a memoTyspaa
Sepavat
to determin
t
iprocesti
Procass
lo24400
Pag epacemo
AApoi lsase linit
spacl
th logico oddess
6
& lspecifi
ioragislers
RIo th aboue{iTthes
holds B0904
base reqisles
is1204
limiteqsates
9 0o
theoproqromconq all acassl
addesse
om 420
300040 to 40
Ondy theOS
only 0s Can loadthebascEnlinit
aotgistea
* Logical memoT address - u
JRebost Systemeboots,TfaSqglerorebo
theLogicaladdss
Shtbe phystcal
istE.
lmunoy
bevanishedoaddsses
will
001
agistes
on uingclacalon
Dynamienelacali
G
E Tf the base i5t lo5,hereaouStx
attioplsa poceSSThen addtSSlocato
sacoes
tcnamtcallq.
to loois
Locaticon
to ocalion
located o5
mapped to 9og
CPO will qeoerale logca address
uoniog
ohilenunninglh mh
proqro MMUwil!
naddthe alu q melocalion ( 1os
register
So th phustcal
is
mmonaddresGorProai
YAddreSS Bioding-
H ispr ss q mappinqfrom one
*Adrss
binding
Can occus at 3 differer
[Link]
i5CompiletirneIfyoukoouw ad compile
timecubere esYdesi in main mernoy
thenabsolute Coderalcanbe cqnrated
} Lo adlime - 1 itiskáoona conpil
me wheretbe processiutwill stde'
thecompi len mustqentrale omelocatab
code & finalbindinq is delayedtil
Loadtime.
he
iisCzecutiontime I{ The procesScanbe
duringts ecution
movec duriog from one
memeTy Stomunto anotherthenbindig
rus
must Be dzayed
untiluntime
Swappiog
I is a Simple meno or protS
managimnt melhod used'
byThe opeyal?ng
JH isiprodeG9 O aprocs5
Swappinq
8to
dbnimain
backinqu
me
)e
stor Csecondar
disk the broughtback
botchavd
mory
main
o
mumo TJ
to
the ezeulo
contiouc
menbTUSnot Enough
olwhence@u
to tmporanily
Stord ulHplepoqrarns
ODheowTTakeg fro9RAM
SomedProqrorm
uQlsbrethemtolhehand bysa
diskb
igpoMachanisCalleoo Swop outSimilony
Caiiwhên broyBoough
RAM isiofrecio to Store
Swap io
Tlhunh
prograims- in thouprograms
Krom hard dsk to RAM.
salgoitbm
Ez?-Tn RoundTobiodscheduling
when atimenuantum [Link] memoT
manags oillsartto Swap outthe proes
inan
6 toSw appedo
thot hs nqustofinished
hea intommorg
procc6S2 spacethahasbecn
deallo
cgted
Can be usedforprio
voriantSwappinqIf a hiqherprforitu
A
ithmTf
thm
alqori 6m
cation
Scheduling for
allo
mcmoTy
processTeguest beo occupied
isahad ful or ithas pre -
dowprioity proCeSGesorOCcapid b
b Somc Theo memoT manag1
ty
high priori prDceSSts
a low piorit9
Can ditrrmie to Swapout
proctssesSo That higherpriorit pocess°c
Gzecutedt5zecutioo thelower
beloaded
processcan now be Swappedinagain
prioity Thisi
tts fxccution
lcontioue UcriatSwapping
Doo Jooor
turodas Roll-orta
policqis
x Advantaqes
The process
processes
This me
belpstheoPU
titoiotheSa
to' nana
rme nmain
thodhelpsto cCreat &u
€ruse
mg
gu nulip
nemoT
imethod
This ?s econ
omifcal.
Bett
ad vontaqts
Dis
Jn the
-osolb
prformance
o
i
CPO.
ase o heauySwappioq
aclivity
power theuser
the ComputessyctrsIoses
if
Space dlloca
alhe art
oT
memoTallocotion
nemoTy altodation
c bl3)Non Contiqeous
9lbou3
altocctio
Cootiqeou'sMemory
9
in onthaooDdoCE6Contieous memoryiallo
all, spact memaing Togeth
theaucilaole memnory
gh
fn ont place TH mansfreclyavailabl
blocksae not Scattred hee& there acros
theswholenemori ispaceo3ci2bidoioy
The main memomis dividedintostwo
oncLportiontsforHos other
partiionsie &
DYD0of2
troario
haaraai
memoryallocalion
) ontiqeous
b)Loben afile C trininates
thuftles
mleasesMhe no
mmerty creat'ng holem
D Fized Siacdpartiion
or StatieConttoa
Memory allocattonom3o2bos0ihooD G
o Here mermoTyisondividedattofi
Cblocks)&
Size partition Each blockconl
ont prodesSButdsastä
ezactly ed part:
Twtllintthe- degre)
qâamutiproqramm
bpo asthe numby o blockotuill
the numbry elth
decid
or (ao
odbrthoo2 eoold
siedpatitioo
a) Variable dynamicCoti
ocation307niso
quou nonyivaume
otteretheacóso
onalysis
thumcmoT
Gtha
Tequirement theoprDcesS
wihasa
memoT blocko
theurcquiredi
athto
sttu tothe
tfiatncntnoyyblock
allocateg
procesS)T
¥ Creotioo
of i
Holes8 aliot potbrn0
Tniötially
the
uhole memoT spaa is
the user procesSesas a larae
Qw oilable
for
blockor bole wheneveTtheprocess large
isani ve
Ro the memoTy the proCESS qats
Executed
Jerminated! memory here theprous
CreatestheSt o holesof uan'able sizesp
x If tbe memor hole istoolarqe forlhe pioa
Ih
into
itgcissplit Two paTTs ontpart
themenmoTyhole isallocatedto the arived
process& theotherpartis etuvned tothe
Set oabolesyuheo a prodcsstrrmin
E thelomtm
Teleases it,
oru allocatedto
he Ts teplad
mleascdimengoYu back
20D thostonholes that
Thetuo holes:
rmrgedttoforr
folesor oneLarghole
Now atthisBoiotos checksohth,this
lavqeholeisableto
X
newlyformedfree
satishy otherad qúcued
processewaiinq
th proLSSalQoesS oniiookdrg
Thre ar 3 ahgorith
Startangies
to Selectthe free hole fomset o holes
D Grst 1) best ft
2r0DociotocnportIomr
D Frst ft stuitsscan
This alqozithmo
fom the beginning
tions serialq
the parti
uohenanEmptol thotis biq ênodqht
iporfion
a Stortthe procšSisfound then thatholeis
toilallocaledtotheiproas$20rsrouCanSay
thifrsthole
altocátes thotiselbi enoughi.
The Si2e o hole hastobe qreatesthano7
3sotleastequaloito theLprocs siaes
2U009
eslo
o War
lo
+ Pie
(12
Fqti bq P
Memorg blocksthotaTe occupied
hgii Empty holes.s
P,PPsa
P
booRef abouefiqore ss Phroso
itproce
I5ktwonts to lallocate memoT thott chooses
Becausciol frst fit itsearohesfor
an
thalisEnoagh
Enyptihole to Storeisthe
spac
r
processC 35 k D
lsk so 5 k ts ocdupied
alaloDiolodoprol ocuotulos
.
* Advanlags Grstft negtitse
Tt is aste
sti searchias
i1f1Seavches
ondythe
HstEmpty blockfs Enoughto
eslo
ocateE n 3n
Easy to all
* Disadvantagestood
Ezlernal
haqmotation
ocurs
oobJastoqe o spacclo17
poinaipsdsf
GtC
fnoughtoStvse prbCess
Shov
B Besttt
allthe
alqoithn
bparions
Ernpty
o
firstS
Thiso
blocks
tfun p7
Cans
itoll
o catesuthc osi
oSmollestzéd tho block
isÉnouo sto stoethatipiocasst
eslooola
ttu Fiqi
Rafert1 1foproces$PiofSi2e
1S k wnts spaaio memoTyThen 20 k block
is allocatd.
because asitscansalltheEmph
mernoTyholesthuoit choosesThe Somallest
thotsenoughto sort-tlatprouss. ho
•Advantaaes
Less wastaqespaaas compared
memoTye efiient asthe
to frst
0S the
allocateg
t
jobot in
process minimumpossibl
spaa
Drsadvantagts
-
oCuTs
Fagmntation
Exfernal
THs theime Consuminq proces S
ernptyholes
Slow,checkscoh all for
o
job makesthe workingq the0s
eachjab
slow
3orst
Gmply
t
memoTQ
IH allth
alsoScasfor
largsst thupro
siztp0titionto ess
the iq11,f proceSS P, wants
rrfr
Exrefr
Spac inmemoT biy using worS fit
it
kSi2ed memoT block
calesthedtoo
Urcalo
9xiH atoibobio2i
hdvantaggs-t3Upr22 ta new
Bdvantags space
23v9TheotDnaining callocated
°Snternal
hagmentaior gsoinaft
occurS
ss can bepla
ccd
cOveYSpa ce thA oTherproct
Disadvontagunind
IH iShtioe processaci2
consumingproeesshsol
Tt fs alsosoulprocss289er
spacefoqontel
Alscald
Bastcalltherrare two typcs
to fragatrit
Tatinalhaqmntationrrnsryplgn
D Ioternal
fragmentation
3-Ewoglingoxagspat
IHoccunts
occuhenThe menoTy
isdivided
ioto ixed Sized blocks whie
processmeguest for [Link]
fd siaxdblockgRs aliocated tos theproS
To case The memoTY assiqnedto fhuprocs
proco
isisomerusht arq 1hantheimehor
iTeauetted theocthe bts assigthe
differeiceo
erequested memoTy
emary
isthcîternalfaamta
* This"leftourr spaceinside theofized
SiRedblock can
notio
processasitaDoQld
toang
be'sallocated
onotossufeiiet to
satisfyThe Tequesto m moTybby the procas
spaL Used
sUsedsp
Used
aotwohdos
Spaco astedaso spaca
4 7515MB T
30 M8attL
spaGcrfor
Ossiarud
Assighudispadfoy
2id
1,5b0M8
Procss proass 500 M6
Joterna wiloccuvsbecau
fragmrstolion
we haueixed sicsi0)the rnernoT blockS
lhisOroblermCan beomemovedif wa uSe
dynamicor variablesi2ed bastiion, &Pac
The processisallocatedonty thatmuch
amountospaceo ashichiismequiTedab fha
proces9 So there is nointenal
fraqrmentati
Woldelioumarcoihosa
)Ezternalfraqmentation d bofipse 0
It o ccuTSwhoTher isai
amount or
Sufficiert
sSatisfu
dhamemoTiquest moTyeoiSavai
butfhe cmemoTyauatlablets to nonhcor
qeousmonne heneprocesssrmemorya
Mequest
caonoto
[Link].0ubsAMOO Dp
XCtther,jouuiappl rsto
or best d memo
allocatioo
stattrquwillCausesEternol
wiT1 a
qmetationor 9
ProceSs1
osAvat
lalbleoenssn
o ProaesS3 oo io
inoanCorligd
clwt
lóan2nnovesithe
EztemalFracamenta
by usinqCompachíon,
bq
inqall he femamoT
meansmTq
Compaction
tocethin ongLarge blsck
Thistechnigur
ts
epAAtai
alsocalledas de kagmentatioo
Thislarge.
block o memoTYishinused foY allocahi
to1he needgq teibs
Spaceaccovdinq thene
proCesSes.d
i)Non1Contiqtous
anosoe
memor allocation
Jo1heino
ContiqtousmemoT
Qllocation
1heavailable
free memor Spau a
andatheeall
scattcred
here fee o tinoT spau
isnot at oneplaceacubsa
ot doliLo the nonrconti
guousmimoTal0c
tion
a processoillacquire
thememory spaa
but itisi not atoncplaceoits attfie
drfe
to the processrequiremeot
Aocations Thistecb
-que o NCMA Tducesthof aslaqocnarno
w Non Contiqous memyallocaionhauing
techniques uo)WiuswputoteOoitooollo
1 Paaing ) Seqmentat
Paging
Paqing thephysical
permits address spa
o a fo be Ttisa fzd
non-contiqous.
proceSs
size
partitioning Tothepaqinqtich
schemt.
the sccondaru
memory & maio memor ar dividu
ióto
equal d-size
partitions.
• Ihe poaqcso proccssar Storediothefame
naio nemorydeprndinq
upon
Theiy
Quaila
o1alhen
paceSiae hamesi2CShould
away!
loeSame
ur onstder
a processSi2¢ is 4 bqlespags
is1bye so we Candiuideioa Process
i6to4 pagcsPo,P, P. and P.
Thatisnurmber Pages size
= process Ipage
4/1 = 4
Translating addrss
the logical intoPhysica
addess:
CPU address.
alwoysqtneratesa loqical
A phuSical addessrsnecded to acces
Deededto sThe
main mernory
followinq art
sleps iowed
fol toraosl
loqtcaladdr
Ss intophustcaladdress.
Step: CPU logtca address
qunerates ddreSS Consi
slingo two paits.
Paqcnumbe ItspecifitstheSpeciftcpaqy
Logical addres
Phstcali
addrss
CPU
Pogcno 90
Po
Po
023kboPa of62tbbo
bPal
PagtTableo Pa
xTranslatioo
tookaside Bufei
ICTLBbinPaginge
iforeach processpaqe
In paging tablewil
be rratedwhichuiM containPagetnlormatton
ikefane numberSome othe useulbitseThispaa
rushere n The maio
tabletalls memoythe actuad tal
A Bqhusingi
acessime
accesse
ricoun
pagtisTesfdinq: 0or
pagtTablet incrtases
due to ioreased
[Link] uses8megoT
eficRencuPres
numbT memo
accesses
Loto qt the fame numb frompagatalble
Gne
anothes
I
is to getpage lot Frorm thu page d
&
TU
x If the process isbtq,thcopage tabks
šiRe
olsobeCorne bq. If we Sore ThigopgtTtabtes
oioTeqistess,tht qislerSmay nst holdalthe
pag talalesbecauseq theii e
Toouy
Siae.
gmallero
-torothis
ComeThisprobleo u sea Small,
special fast oti ke
Lookup blw issetupfor page tables
Called
TranslationLookasideBaferCTLBD.«piCi E
TLBnas high spead logemoTnyedto keepitack
Teanlq yed transcalion
gCcMostaiedpaa tallatht
parisdots
C Paqe unbeyand
frarmenumber.r
23223030
19 with TLB
tardawae
Poging
addres
Logical
CPU
P NooframNo
iTLBbit
hiPhusteal
addess022o
331 bd o
Eidscdu
o0ipo 2
TLB 3004
TLB toiss
22xrbb0 eoip
Paqesid lilsoal
The TLBContainsonlya a fewo fhepage
TUB hit.
Tocase ifthc page numbe isnotfn the TL8
Asboo
3
2 C 2
5
Leaical
eumol4 tasle
Paat 9
Stconco
Cmimoye muhort
Seqmentation
Deqo is a memory manaqiment
Searnentation
iowhich
tacbnigue the roemorpisdivfde tito
sGtheNá[Link] a
whichCan be allocatedto
b
La [Link]
i Cach Scrntnthas a namiand itslenath
Consi dér0 is
Proqpan lkhgth
s
into Seqnunts
idiytdedos
21)
slack
Subbol
Subouti 4oble
Seg 4eD)
omain 2Dpr
eieSq 62
vt Scqmird 22scbbod
Stal1
As
program a
isa
Stgnment loqical susasi
it nay any
function,
be
untt nais
datastruc
-üTNS like stack queue,araqs, trees elc
for ur s tmplermen
lation Scameols aTe
Easy
numbrde mefereocedby seqmntnunbes
catherthanStqment name
fach Seqmertare stored
Tbe detailsabort
io Tablecalledsegmesttable.
a
Seqmeottablestoresa ioform
Tbe ateon :
:
* Base Ttis stantingaddress q Seqmar
Linit
3 Itislengthq the Seqment
PIostqmentatio thelogical address
Consis
poits
Seamerit numbes:SpecißiestheSpecif'c
Seqmend g th processfrom which cPO
wonttoadthu datao2 O000
bs Scamieadoffsct the specific
Specificieg
sCwoxd iothe Seametthat0026
CPU wantsto eod
00
for thenqintrated SequrtinumbeyConspon
ingeAtrys locald intheoSeqrmend
talle
scarurt atfsctisComparedwiththusiz
baoel
Climit the Segmurtoabreno
Two Cagey ar posible,do
(2)
Lcase >= ligit
Seqment offset
if
if Segntoffsc
fssound thoe
tobeqreales
i.
equaltolimit a tropis genratd
Case Stamentoffse irnit
thenTeqursts troledas a Nalid eguest
isad ded to the
tnt offset
Theo Seqn
Fig Stqmnta w
s
baseaddtss the seqmetto phqsical
lian
Limt4 base
Segment
GRU &otolaoni w
table
yes
lel 2ii
Pianobtrapi erro inoPhysscal
addmssing
Segmesdtalle
iBase
Lint
1000
300o o0
bsbnSeqmuntrdl
4940
Stamuad
rScanent O900
Consideran Qccessing
to ngtruclauetfonj loca
atan fßetCll4)*%buk 876nooL0D
ot
The CPU wants to efey4hi
pyte in seqme
bybmappinqaong
uo-nt3then
314<2bolan
limittue,ttheolimit
o Seo
Advantages
Tt allous odivrdeproqvomintomoduleSo
battruser uiguali
Seqmeoswhich prouides
Hsolues leminternalfragmeo
itfheprolb
Jeqnenttale lessSpavag
foConsanes Cornpaved
2223etupagitalsleoraat2
ot rORo
%10bbtesatbhacgr
*Disaduantogu M
ternalfoqmeno
headsutoi
Th Segtntotion
bastosuitedfox
Seqmant o unequansi2eAre
batwuo pagioq
&o Seqmentatio
DifferencLs
Itma Paging
hadordrns
ooSeamentat
ad togr
fagmertot
omnttation ezternal
iottrnalra
theblw
s si2evi
Thecseqmet
do poqing userL
decides si2tl Specifiedivbu
thekpage
A processaddrSSpaaf oo
AupTOCESS addess
sd Spaceisbroken to
indif
isbrokeoiito hzed
s whichistalled nisizedbloct
are
block
Pages. bbpbioocaltedseo E
i
Toe pagtngtichniqut
faslexfu oneonoYUaess
is.
Seamurlahon slowe
Than paqingmdhed
talllsorsthe
Paqt
slor
Sernentatiortab
opag databo tuStgnentaon
data.
VirtualMemT addresSmoTe
Smnem
ComDudes Can
Aameunt
e
Computes
phsicallq ostalledon t.
thaothe
SuttemThis Eza menoryis ig CalledbiTtual
m.
menoTislTequimd
ohyvitual ba
oINQuheneven
nConpuoes nothavespauBo fhe
mmory to stoTeprocesses
(phystcal theoprocess
ae
aTE stovedin Secondam mermory agtr gettog
Spagio SMfhe Stordprocešsint
ointo
thc PM SovitualoemorUtUsesthe
[Link]
COnce ha2
x IovM the omplateproqram oeed tobe
plaaa
ini memorycutngEzecution. fore instta
there g
Tuoningong onq proCeSS in enath memoTy
tmoTy.
the
Os doadsNariouspartsCpaqts) notc than on
coPag obolddooea
sforr23o
ot
Pagt
Main m emory
20 Swap
Page
viclua)trmat paa
tole
pagts poipo
Brote eas90Sttsndaty memory
uillmaps
oiAs oaboUefiquwiTtualomemo
caloddres
s)toaphsi
addwYeSS Cpaqe
theilogicalo
[Link] paqe is prsen
that
by usinqiopag lod
in maio omoytoT hatddiskora
aitsdatattoa
be paqcsore napped6Sends
or otohard diskaoub
phusicaliroomoT
I heimain mtrmoru docsnot Contoio
thepag
gt
whichhas mapped b paqetable,theo
back from tHD by usingSwap'io
sthat page
30proceSSno)pipog onpmsbbbar
Tf thephysicalimmory
thl
isofullgthe pag
ISwappedbut
Teplaad toHD:
Aduantaqes
The
- load&
aoiity to Gzecutoa process
Tthot
otarqT
rquirs Gmaunt q memorythaowht
a Tarqeramount
is alesb loadinqthu
ougilable by procesS inpas
uE tho fzecute
[Link]
Pun laratrproqraomsl Pm Lphast
wtlhless
advantaqes
Dis
Cons
umeS the StoraqeSpa« a harddisk
TttokesmoTt imeto s oitchblw applicati
proqrammesCan un
slouly
x mtmoT isimplemrtd
Vitual by usingdemand
paging
Dermand Paging
A demngnd paginqmechani
sm isveT.
to a paqing Systemwitk
much similag
Suappingwher processesstored theio
onl on demandnot
poges orehoaded io
adugnccAccoTding to theCornCapto VM inotda
ttozecule iaoilprocess
itis not nescesSarThat
the whole processshould
prsent in mainmmor
at the qivtohimcBu bow Can wedeciden
aduancewhichpage should inmain
beapresent
oo mernoTat otime
donpavticulax &which should
Got lhereono0a
b
aosab ToiSolwe 1hisdemandpaqingqi
Cónipt
Totoduad
demond paqinqconapt
E
Says cde
Shouldoottood an paqe intothe mainmDO
cai quired o
we shoadkoep all
thepaqesfo
Secondarymemory untldmanded by CPO.
Hence it s called aslaz Suappesbeca ge
se
qpags
thosaapping itsdonenonlyuwh equi
byCPOigRgDenand
Paginq
Pr
A
B
P E
theo Ue Calltaspaqefault,
ouTsotheqrequird paaehasto fotchedfror be
mainmino•
Secondaymemor to maio
io)f9n
Can beuilisedith
b
beterefetc
siMemory
Memorg
to
Ifang
Tf islavqca
proqram To physicamemn
thenithlpstoTun his proatom.
No fxtrnalfagmentation
Eosyto Swap oll pages.
Disaduaataqesi
•Toternol
e
nay OccUrS.
Rogmntation
MemoT ocous Tocislonget.
acceSs longer.
L
Po
62 ulomà Pageto SM
eferena Pi
aPOdo bring
bact
pdae Pt
Pdaitoblnd
isked
fn
Mainmemoi
Stept
Check 1hea gcthc
location irefrenadi
poging
pagetalle
iofiq Tthc
wansto accesspagl
GRO
Poofpoes5oftrstitiwtlthScatchitfe
pag in th
le.
Pag tal
not contain
3, IfThe paqe tobledoes) the pag
mol ht paqefaultoccuxsSo in
[Link] equesTedpoq
cby cpu iso
not present inpaqe tableso now"i
will be o page fault.
s soonas thopaqe
fault
OccurS the tontrolaqocs
to osulqp
n34The O wilputthe procssinwaiting
state
blockedstate now 0S wil| Search that paqeio
stoneeriseCodaryponenoryo
backing,
4sTheOS witothen tadthei
pag frómthe
loadoittoThepmain cnoTy
backingstoru& me
* Paredenandpagin puTedemandpaqin
paqeisnot
euen a Stogle loaded
iTo
toto memor
if Causes a paqe faultIo
ioitiallyhence suc
Case the 0s setstheinstruction theprcess pf
wbich is on a 00 emoty tesidlent
a [Link]
processimmediately fos page,
faults fte the
paqtisbrouqhtitoimemor.
0oítenslax
x Pagefaul
PaqeReplacementAlqoithmil?sta
e iscdoneben be
Paqe meplacement
page?s not found in the mainmenmor
nequested
Cpagefaulthe
te aeuavious
plaaneplacimee
ffeot
method
1Eacho
alaorithot of whbichohasladi
Du wbichthe paqe Can be eplacedg o
are3Typeslo
XMaiolynThare PRA.mo0k
iy FIÉoroEint
Ast out]as0ole 02
First
pageireplacnentalqori
Eoptinmal i
Last ecertlyus
isnot
notaleady
aleady
paugeis
FauHst-The
fage [Link] memo
Hit-The|ggeio aleady lein meo
Civatlab
Out)g acE Ee
TOyeTEO
tFIFO Cist ToGrst
Tbiss thesimplest
tht pag plaumertolaoitt
Jo 2
Tn 0S
thistht keaps hck
hck ioallpagsi n indth
4
In
Husthetmai
eplates
H paqc that hasbeer F3
the oldest
thoimoioc
Sert in
prt nenbruHorthelonqtsttime
F,
Beladys Anomalhis phenonena O CCuss
Explantion xIoitatly
for Eztr atloslols
tmpyslstswith3
, are
paátfaulTsndgyp
toth
So cohen 3,0 Come thy aTe allocated iitL
xohto3camesitis alodio nernoyS0
ocoritnisipage
hitatbanattona0ng bas
kheo aComesaitis in menory
not auailable
bo Sonithepla
cesthe oldestpage slot
EE1 witt
Onne
*GComes. itsis
iS0
At tast
alSonot
in3(ones
pag
thememoTtx
sOvailalbleio
the oldestt
Tploces
itSnotayailasle
So itTe
3
n
sloti
o) to t
placesf sot(at uthpag
Pag fault.
3
Dh Consides stríngA.0.1.2,0,3,
à paqeimeftrence
do,4 2, Bo,33.2o with 3 paqe fames,
Findthe numbe ) paqefauttsand hits.
3o 423
4 o 3 2o
F, K k
3 3
B 3
9
4
2k
4d
332 1
|O
oH H
IONu H
92|r B222 3
F3al
L9
33b33 33
a22d 1SSSs 8| 83
1X55 44
H H % H
Hits= Gsmlar o
ik LRulteast
yneCeotlq
used)
paqeeplaca
nent
[Link]
Sugqesls
onThe principle
woTkS
alquit
irthis
easteCertly
used
thepage hati
Tt replaces vhagenotbeeo)
Atiurefe
ired b the CPU fosThe lonqcsttime
(fas
EosConsiderpaqerefernu
sting 234.5.J,
3,1G,3.5, with4 4 paqefanes,Findthe
B
I,
number frames & hitsusing LRO.
Hme
4
4S,4C
4
3 3
4
fa 3 3 3 33
1 55
5
H H H H
onumbespaqeHits
faultsA
numbrr
lo4
O8
:Hhut
Explanation rogoodau
ToitiallyallthcHslotsare fmply so when
.2.34 are allocated to the Ernplyslots fouY,
4 paqt fautt$
*NowSConnes
poccaTS)t 30DQ bieno) e oo
&iipaqe5 islnotprsert
i
maio memor h enapagu
in
fault0cCuTS SoITepla
8 it i0 fe slo bcz that s least
mecentls
used past i
*CPUTequtst page
paqt1aqaio paq 1 isnot
presttt htocepaq
faultoccurs. t io
Eslotat thtisloaste Centlueplak
cised
ow cpuTequest 3
io main memoul paqesobch
X
are alrrady
presert itisapaqc hit. So
DL
no Teplaameit.
Now CPU TequeSt pagL pagGit
isnot present,
fthepoq faultoccuts&lgeplacetit hante
tn F4 lst
ikethtsfollouw fOY2 used'in past
Detandn8
Ob Consid
er pageTereng
Cooa
pages.
latogua
slring0,
2o, 3,
rameSize
4 fnd thenumber fautts
hits
o 4 2-3
2 22 22
aooo3 3
b4 4
2
Oo
H H H H
* X H H H H
H H H. H H H
00l' Jumberopagpfaultso=
o Goibor
hitsFo
l0G
if
:
Ezplanation
allslots
Joitialty are Soiwhec)
1.
2,3.44 Cam Jhy geallocatdo
theEmpty
o
slotsinorder their,
anivalThis
isfaultsas
,
|O 2,1when
4 35 Qre s90t
S
auaiablei
main nemo
in
itisnot auatlable
Comes,
mtmor pagfault Teplac
wbichis
4 qorngtobe used to
fusthey
future among B4E
H
oheoacomes
thyane Ovaila
inthe eapagehit so
memorqiei Só no pa42
tot.
Tplacem
wbeoGComes,t is not auailabl in
So paq faultooccus
mmoTyohen1323 f itrplace 1
comeS,RtislCavat\a
ninthimemoTQ ineepagehit
bitgbs6 rao
rio
pag
iplacemest [Link]
Err 2t
3.0. 2, 3,o
2.3,o
4
fnna
Consider
82.I,2004 o,6A
Ting
paq mftrnastingA,D,1,2
witt
4 fame5 find
the number
paqL faults ond
hits.i sbieo
03O 42 3 o 3
2 222
fe
fa
1 X4414 4 4 4
Fi 7||73233333333|3
HH * 333
H H H H H H H H H
H
Nurnbtyo) faults
H H
clno. hils
Hit gotio Tot X lO0
Tota no. Teferenas
oibspla
Faultsaiolotal
ümbrofaaltsx lod = XI00
eeencasop)
to ohroaproqrom 0ed spaa
process
sthanRAMorit cedospace whenRAM
largtr
isfault 0s wil|Tr to allocalespacofrom
SecondaymemoTyand behaUes ikc4 has
thatmuch amountq mern0TQ by Seruingto
that proqram
or proccssCuintualrnenor
wekno w that Euery proqram process
is
iotoSomt paqesawbeoo ptoqrom
divided neds
apagewhich is not ioRAMpCmaiymunoTu,
ipaqefault
tha isLCalled
faultoccursoS oil
s whentUTa pagpag
htryitofetchsthatpag
fromiSecondarymenoqa to suwap it
oswithon e thepogeinRemlesaapping
?nt miitboo
Defn-Thrashing
eDY Tfthepage faultandn
anda
Swapping
happrning veTyhequntl thenoS has to
2233019
31233orgooo
sldolio0D
boo
Degteeq alipugrioing
(36
22c
q multiprogromminq
•the maimum
Degree
numbeY
iTtdesei
sststhat
proCt
Singleprocesso7
Sysleom can accomalate
oriotuL
efficiertu.
The abilit9 an 0s to Ezeca
mort thanoneproqramon a Singleprotssoy
[Link]
bo ma Intheqiutndiaqramioiial
dqree o
mttiproqrammingaptosomc fzlent
o time
the CPO tili2tioois VeThiqb 6 thususti
De eSouYcesaTeo tilisedoo Ba ifwe furth
incrase thedeqre9s multi proqrarnming
t6e
CPU. tili2attonwtlfall down thesuste
E
willspent moYe limeonl inThe pagL Tepla
-mnt and th tirneta ken to Comple the
aExccutiooo thecproceSS oilt
increases.
970
Causesg Thrashing
s High deqreq muttiproqo mming o
T the numbero processes
increasinginthe memorythan keeps
number o
fomes tocatedto each process willbe
decreased.
So,lessnumbezo hamescuillbe
[Link] tothis aa page
page
faultswillocçurMore
CPO time wil be
frequentlyand moTe
bc wasted in
in out o paqesand the just
& Swapping
wl
tili2ation
keep on decreasing
Locksofames ootlroas
&
bep3d
Ifn pocess lnurnbeto
hasnlessi
famesthan lesspage o thatprocessuill be
iable inmimor
to neside henceimoTe
&
by appluingglobalpaqe meat
neplact
locallpage ment
meplace 16olio30
ea1to paqei
Global -7he paqing
Teplacement
iapplicdotoall
3Yalqoithm 1hepagso The
owhichprocess
memoT neqadless
Owns
bothemApaqe faultinoneprocess mau
Local paqtTeplacemert i
where a process
ioitsown
Can ool be allocatedpages
Teqiono memoT or itSele cts The pagcs
tothatpOCCSS. S
which onl belongs
tbee achanceto
1s_ meduce the thrashi
thrashingbased
to handle
Techoiques
:
model-Thismodelis
Wosking set pagc used necent
f
on localt.
Jocalfy isthe
Locality
and alsothe
usedagaioand agaio
Can be
also
whichare nearby thispage wll
pags.
be thesct
[Link] Setomeans o
Paqe
} faultfrequency uhenthroshi
ithas a few ngmbe
Th
OccuTSawe knowthdt
aofameS, Basedoo this, we assiqn
id2appr oaerboind
& foTthe destd
fautti
gatts ofccordinq
toapagefauttsate
Cwe allocate or Temovepaqs. T the page
faultratebecomes less page
tha lowerJimt
hames canbetremo VedromtheolproCeSS
SimilarluifthepagefauttTaleisornor
o than upper boundo thenhmoTe number o
Framescan benallocaedto
tbe prOCeSSiand
fno framesaTeauailabledue
To bighpaqe
fault ate,Suspendtheprocesses
&mresta
itagaiowheo frames become auailabl
6oopdoo2iisr
92
Operating System Handout
File Types
2. Direct Access
• Sometimes it is not necessary to process every record in a file.
• It is not necessary to process all the records in the order in which they are present in the
memory. In all such cases, direct access is used.
• The disk is a direct access device which gives us the reliability to random access of any
file block.
• In the file, there is a collection of physical blocks and the records of that blocks.
• Example: Databases are often of this type since they allow query processing that
involves immediate access to large amounts of information. All reservation systems fall
into this category.
In brief:
• This method is useful for disks.
• The file is viewed as a numbered sequence of blocks or records.
• There are no restrictions on which blocks are read/written, it can be dobe in any
order.
• User now says "read n" rather than "read next".
• "n" is a number relative to the beginning of file, not relative to an absolute
physical disk location.
Advantages:
• Direct access file helps in online transaction processing system (OLTP) like
online railway reservation system.
• In direct access file, sorting of the records are not required.
• It accesses the desired records immediately.
• It updates several files quickly.
• It has better control over record allocation.
Disadvantages:
• Direct access file does not provide backup facility.
• It is expensive.
• It has less storage space as compared to sequential file.
Swapping:
• Swapping is a mechanism in which a process can be swapped temporarily out of
main memory (or move) to secondary storage (disk) and make that memory
available to other processes.
• At some later time, the system swaps back the process from the secondary
storage to main memory.
• Though performance is usually affected by swapping process but it helps in
running multiple and big processes in parallel and that's the reason
• Swapping is also known as a technique for memory compaction.
• Swap space is a space on hard disk which is a substitute of physical memory.
• It is used as virtual memory which contains process memory image.
• Whenever our computer run short of physical memory it uses its virtual memory
and stores information in memory on disk.
• This means that given the starting block address and the length of the file (in
terms of blocks required), we can determine the blocks occupied by the file.
• The directory entry for a file with contiguous allocation contains
1. Address of starting block
2. Length of the allocated portion.
• The file ‘mail’ in the following figure starts from the block 19 with length = 6
blocks. Therefore, it occupies 19, 20, 21, 22, 23, 24 blocks.
• Each file has its own index block which stores the addresses of disk space
occupied by the file.
• Directory contains the addresses of index blocks of files.
Advantages:
• This supports direct access to the blocks occupied by the file and therefore
provides fast access to the file blocks.
• It overcomes the problem of external fragmentation.
Disadvantages:
• The pointer overhead for indexed allocation is greater than linked allocation.
• For very small files, say files that expand only 2-3 blocks, the indexed allocation
would keep one entire block (index block) for the pointers which is inefficient in
terms of memory utilization. However, in linked allocation we lose the space of
only 1 pointer per block.
1. Single-level directory –
• Single level directory is simplest directory structure.
• In it all files are contained in same directory which make it easy to support and
understand.
• A single level directory has a significant limitation, however, when the number
of files increases or when the system has more than one user.
• Since all the files are in the same directory, they must have the unique name. if
two users call their dataset test, then the unique name rule violated.
Advantages:
• Since it is a single directory, so its implementation is very easy.
• If files are smaller in size, searching will faster.
• The operations like file creation, searching, deletion, updating are very easy in
such a directory structure.
Disadvantages:
• There may chance of name collision because two files cannot have the same
name.
• Searching will become time taking if directory will large.
• In this cannot group the same type of files together.
2. Two-level directory –
• As, a single level directory often leads to confusion of files names among
different users hence the solution to this problem is to create a separate directory
for each user.
• In the two-level directory structure, each user has their own user files directory
(UFD).
• The UFDs has similar structures, but each lists only the files of a single user.
system’s master file directory (MFD) is searches whenever a new user id=s
logged in.
• The MFD is indexed by username or account number, and each entry points to
the UFD for that user.
Advantages:
• We can give full path like /User-name/directory-name/.
• Different users can have same directory as well as file name.
• Searching of files become more easy due to path name and user-grouping.
Disadvantages:
• A user is not allowed to share files with other users.
• Still it not very scalable, two files of the same type cannot be grouped together
in the same user.
3. Tree-structured directory –
• Once we have seen a two-level directory as a tree of height 2, the natural
generalization is to extend the directory structure to a tree of arbitrary height.
• This generalization allows the user to create their own subdirectories and to
organize on their files accordingly.
• A tree structure is the most common directory structure. The tree has a root
directory, and every file in the system have a unique path.
Advantages:
• Very generalize, since full path name can be given.
• Very scalable, the probability of name collision is less.
• Searching becomes very easy, we can use both absolute path as well as relative.
Disadvantages:
• Every file does not fit into the hierarchical model; files may be saved into
multiple directories.
• We cannot share files.
• It is inefficient, because accessing a file may go under multiple directories.
Disk Organization:
A physical structure of disk is a memory storage device which looks like this:
• The disk head can read or write data only when the desired disk surface area is
under the disk head.
• Read-Write(R-W) head moves over the rotating hard disk.
• It is this Read-Write head that performs all the read and write operations on the
disk and hence, position of the R-W head is a major concern.
• To perform a read or write operation on a memory location, we need to place the
R-W head over that position. Some important terms must be noted here:
1. Seek time – The time taken by the R-W head to reach the desired track from
it’s current position.
2. Rotational latency – Time taken by the sector to come under the R-W head.
3. Data transfer time – Time taken to transfer the required amount of data. It
depends upon the rotational speed.
4. Controller time – The processing time taken by the controller.
5. Average Access time – seek time + Average Rotational latency + data
transfer time + controller time.
Basically, hard disk can be divided in the logical structure in the following five logical
terms:
• MBR (Master Boot Record)
• DBR (DOS Boot Record)
• FAT (File Allocation Tables)
• Root Directory
• Data Area
1. The Master Boot Record (or MBR)
• At the beginning of the hard drive is the MBR. When your computer starts using
your hard drive, this is where it looks first.
• The MBR itself has a specific organization. The size of the MBR is 512 bytes.
• The boot loader is the first 446 bytes of the MBR. This section contains
executable code, where programs are housed.
• The partition tables are 4 slots of 16 bytes each, containing the description of a
partition (primary or extended) on the disk.
Here is how to describe a partition:
• State of the partition (inactive partition bootable) - (1 byte)
• Custom heads at the beginning of the partition - (1 byte)
• Cylinder sector and the beginning of the partition - (2 bytes)
• Type of partition (file system, eg, 32 fat, ext2 etc ...) - (1 bytes)
• Head of the end of the partition (1 byte)
• Cylinder sector and the end of the score - (2 bytes)
• Number of sectors between the MBR and the first sector of the partition - (4
bytes)
• Number of sector of the partition - (4 bytes)
• The Magic Number is two bytes used to determine if the hard disk has a
bootloader or not. If it does, the magic number should be equal in value to
hexadecimal 55AA.
the hard disk drive into the main memory of computer and give the systems
control to the loaded program.
• Previously the root directory used to be fixed in size and located at a fixed
position on disk but now it is free to grow as necessary as it is now treated as a
file.
RAID 1: Also known as disk mirroring, this configuration consists of at least two drives
that duplicate the storage of data. There is no striping. Read performance is improved
since either disk can be read at the same time. Write performance is the same as for
single disk storage.
RAID 2: This configuration uses striping across disks, with some disks storing error
checking and correcting (ECC) information. It has no advantage over RAID 3 and is no
longer used.
RAID 3: This technique uses striping and dedicates one drive to storing parity
information. The embedded ECC information is used to detect errors. Data recovery is
accomplished by calculating the exclusive OR (XOR) of the information recorded on
the other drives. Since an I/O operation addresses all the drives at the same time, RAID
3 cannot overlap I/O. For this reason, RAID 3 is best for single-user systems with long
record applications.
RAID 4: This level uses large stripes, which means you can read records from any
single drive. This allows you to use overlapped I/O for read operations. Since all write
operations have to update the parity drive, no I/O overlapping is possible. RAID 4 offers
no advantage over RAID 5.
Mr. [Link] Page 16 of 17
Operating System Handout
RAID 5: This level is based on block-level striping with parity. The parity information
is striped across each drive, allowing the array to function even if one drive were to fail.
The array's architecture allows read and write operations to span multiple drives. This
results in performance that is usually better than that of a single drive, but not as high
as that of a RAID 0 array. RAID 5 requires at least three disks, but it is often
recommended to use at least five disks for performance reasons.
RAID 6: This technique is similar to RAID 5, but includes a second parity scheme that
is distributed across the drives in the array. The use of additional parity allows the array
to continue to function even if two disks fail simultaneously. However, this extra
protection comes at a cost. RAID 6 arrays have a higher cost per gigabyte (GB) and
often have slower write performance than RAID 5 arrays.