0% found this document useful (0 votes)
20 views

Operating System Ansh

Uploaded by

abhayjadhav1281
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Operating System Ansh

Uploaded by

abhayjadhav1281
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

2023-24

Acropolis Institute of
Technology and
Research, Indore
Department of CSE
Submitted To: Asst. Prof. Mayur Rathi
(Artificial Intelligence & Machine
Learning)

Operating System (AL501)

Submitted By:
Ansh Dube
Enrollment No.: 0827Al211016
Class/Year/Sem: ALT-1/3rd / 5th

[LAB MANUAL OPERATING SYSTEM (AL-501)]


The Objective of this laboratory work is to introduce the concepts of operating systems, design principles of operating systems and
implementation of operating systems also Simulate and implement operating system concepts such as scheduling, deadlock
management, file management, and memory management

Page | 1
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH,
INDORE

Department of CSE (Artificial Intelligence & Machine Learning)

CERTIFICATE

This is to certify that the experimental work entered in this journal as per the

B. TECH. III year syllabus prescribed by the RGPV was done by Mr. Ansh Dube

B.TECH III year V semester in the Operating System Laboratory of this

institute during the academic year 2023- 2024.

Signature of the Faculty

Page | 2
About the Laboratory

An Operating System Laboratory is a specialized computer science laboratory or workspace designed


for students and researchers to gain practical experience in working with operating systems. These labs
are an essential component of computer science and engineering programs. Operating System
Laboratory Bridge the gap between theoretical knowledge and practical skills related to operating
systems. By offering a controlled environment for experimentation and learning, OS Labs enable
individuals to develop a strong foundation in operating system concepts and practical skills that are
essential for success in the IT and computer science fields.

Page | 3
GENERAL INSTRUCTIONS FOR LABORATORY CLASSES

⮚ DO’S

✔ Without Prior permission do not enter into the Laboratory.

✔ While entering into the LAB students should wear their ID cards.

✔ The Students should come with proper uniform.

✔ Students should sign in the LOGIN REGISTER before entering into the laboratory.

✔ Students should come with observation and record note book to the laboratory.

✔ Students should maintain silence inside the laboratory.

✔ After completing the laboratory exercise, make sure to shutdown the system

properly.

⮚ DONT’S

✔ Students bringing the bags inside the laboratory.

✔ Students using the computers in an improper way.

✔ Students scribbling on the desk and mishandling the chairs.

✔ Students using mobile phones inside the laboratory.

✔ Students making noise inside the laboratory.

Page | 4
SYLLABUS
Course: AL501 (Operating System)
Branch/Year/Sem: Artificial Intelligence & Machine Learning / IV / V

UNIT I: Introduction to Operating Systems: Function, Evolution, Different types of Operating Systems,
Desirable Characteristics and features of an O/S. Operating Systems Services: Types of Services, Different
ways of providing these Services– Commands, System Calls. Need of System Calls, Low level
implementation of System Calls, Portability issue, Operating System Structures.

UNIT II: File Systems (Secondary Storage Management): File Concept, User’s and System Programmer’s
view of File System, Hard Disk Organization, Disk Formatting and File System Creation, Different
Modules of a File System, Disk Space Allocation Methods – Contiguous, Linked, Indexed. Disk
Partitioning and Mounting; Directory Structures, File Protection; Virtual and Remote File Systems. Case
Studies of File Systems being used in Unix/Linux & Windows; System Calls used in these Operating
Systems for file management.

UNIT III: Process Management: Concept of a process, Process State Diagram, Different type of schedulers,
CPU scheduling algorithms, Evaluation of scheduling algorithms, Concept of Threads: User level &
Kernel level Threads, Thread Scheduling; Multiprocessor / Multicore Processor Scheduling. Case Studies
of Process Management in Unix/Linux& Windows; System Calls used in these Operating Systems for
Process Management. Concurrency& Synchronization: Real and Virtual Concurrency, Mutual Exclusion,
Synchronization, Critical Section Problem, Solution to Critical Section Problem: Mutex Locks; Monitors;
Semaphores, WAIT/SIGNAL operations and their implementation; Classical Problems of
Synchronization; Inter-Process Communication. Deadlocks: Deadlock Characterization, Prevention,
Avoidance, Recovery.

UNIT IV: Memory Management: Different Memory Management Techniques –Contiguous allocation;
Non-contiguous allocation: Paging, Segmentation, Paged Segmentation; Comparison of these techniques.
Virtual Memory – Concept, Overlay, Dynamic Linking and Loading, Implementation of Virtual Memory
by Demand Paging etc.; Memory Management in Unix/Linux& Windows.

UNIT V: Input / Output Management: Overview of Mass Storage Structures, Disk Scheduling; I/O Systems:
Different I/O Operations- Program Controlled, Interrupt Driven, Concurrent I/O,
Synchronous/Asynchronous and Blocking/Non-Blocking I/O Operations, I/O Buffering, Application I/O
Interface, Kernel I/O Subsystem, Transforming I/O requests to hardware operations.

Overview of Protection & Security Issues and Mechanisms; Introduction to Multiprocessor, Real Time,
Embedded and Mobile Operating Systems; Overview of Virtualization.

HARDWARE AND SOFTWARE REQUIREMENTS:

S. No. Name of Item Specification


1 Computer System Hard Disk min 5 GB
RAM: 4 GB / 8 GB
Processor: Intel i3 or above

Page | 5
S. Name of Item Specification
No.
1 Operating system UNIX/Linux/ Window XP or 2000
Editor Python3.7 IDLE, Turbo C/C++

RATIONALE:
The purpose of this subject is to cover the concepts of Operating Systems in terms of Theory and
Implementation. The syllabus provides all the essential concepts of Operating System.

PREREQUISITE:

Experience with a high-level language (C/C++, Java, Python) is suggested.

COURSE OBJECTIVES AND OUTCOMES

Course Objectives

1. To make students understand the importance and overall functioning of an Operating System.
2. To acquaint the students with the concepts and principles that underlie the modern Operating
Systems, and to provide them an insight in the working of its various modules

⮚ Course Outcomes

At the end of the course student will be able to:

1. State the core concepts of operating system, evolution and types of operating system.
2. Describe the concept of file and disk management.
3. Illustrate process concepts, inter-process communication and deadlock.
4. Illustrate memory management techniques.
5. Understand the concept of I/O management.

Page | 6
Index
Date of Page Date of Grade & Sign
S. No Exp. Name of the Experiment No. Submission of the Faculty

1 Case Study of different Operating Systems and


evaluation of Operating System. (CO1)

2 Case Studies of File Systems being used in


Unix/Linux & Windows; System Calls used in these
Operating Systems for file management. (CO2)

3 Write a program to implement FCFS CPU


Scheduling Algorithm (CO3)

4 Write a program to implement SJF CPU


Scheduling Algorithm (CO3)

5 Write a program to implement Priority CPU


Scheduling Algorithm. (CO3)

6 Write a program to implement Round Robin CPU


Scheduling Algorithm (CO3)

7 Write a program to implement Banker’s Algorithms.


(CO3)

8 Write a program to simulate Memory Allocation


Strategies (First fit, Best fit and Worst fit). (CO4)

9 Write a program to implement various Page


Replacement Algorithms (CO4)

10 Write a program to implement various Disk


Scheduling Algorithms. (CO5)

Page | 7
Program Outcome (PO)

The engineering graduate of this institute will demonstrate:


a) Apply knowledge of mathematics, science, computing and engineering fundamentals to computer
science engineering problems.
b) Able to identify, formulate, and demonstrate with excellent programming, and problem solving skills.
c) Design solutions for engineering problems including design of experiment and processes to meet
desired needs within reasonable constraints of manufacturability, sustainability, ecological, intellectual and
health and safety considerations.
d) Propose and develop effective investigational solution of complex problems using research
methodology; including design of experiment, analysis and interpretation of data, and combination of
information to provide suitable conclusion. synthesis
e) Ability to create, select and use the modern techniques and various tools to solve engineering problems
and to evaluate solutions with an understanding of the limitations.
f) Ability to acquire knowledge of contemporary issues to assess societal, health and safety, legal and
cultural issues.
g) Ability to evaluate the impact of engineering solutions on individual as well as organization in a societal
and environmental context, and recognize sustainable development, and will be aware of emerging technologies
and current professional issues.
h) Capability to possess leadership and managerial skills, and understand and commit to professional ethics
and responsibilities.
i) Ability to demonstrate the team work and function effectively as an individual, with an ability to design,
develop, test and debug the project, and will be able to work with a multi-disciplinary team.
j) Ability to communicate effectively on engineering problems with the community, such as being able
to write effective reports and design documentation.
k) Flexibility to feel the recognition of the need for, and have the ability to engage in independent and life-
long learning by professional development and quality enhancement programs in context of technological
change.
l) A practice of engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and entrepreneurship.

Page | 8
Acropolis Institute of Technology and Research, Indore
Department of CSE (Artificial Intelligence & Machine Learning)
Group / Title:
Lab: Operating System (AL501) Case Study of different Operating Systems and evaluation of
Operating System
EVALUATION RECORD Type/ Lab Session:
Name Ansh Dube Enrollment No. 0827Al211016
Performing on First submission Second submission
Extra Regular

Grade and Remarks by the Tutor


1. Clarity about the objective of experiment
2. Clarity about the Outcome
3. Submitted the work in desired format
4. Shown capability to solve the problem
5. Contribution to the team work

Additional remarks

Grade: Cross the grade.


A B C D F

Tutor

1 Title: Case Study of different Operating Systems and evaluation of Operating System. (CO1)
2 Neatly Drawn and labeled experimental setup

Page | 9
3. Theory :

Types of operating systems: -

 Single and multitasking: -A single-tasking system can only run one program at a time, while a multi-
tasking operating system allows more than one program to be running in concurrency. This is achieved by
time-sharing, dividing the available processor time between multiple processes that are each interrupted
repeatedly in time slices by a task-scheduling subsystem of the operating system. Multi-tasking may be
characterized in preemptive and co-operative types. In preemptive multitasking, the operating system slices the
CPU time and dedicates a slot to each of the programs. Unix-like operating systems, e.g., Solaris, Linux
support preemptive multitasking.

Single- and multi-user: -Single-user operating systems have no facilities to distinguish users, but may
allow multiple programs to run.Multi-user operating system extends the basic concept of multi- tasking
with facilities that identify processes and resources, such as disk space, belonging to multiple users,
and the system permits multiple users to interact with the system at the same time. Time-sharing
operating systems schedule tasks for efficient use of the system and may also include accounting
software for cost allocation of processor time, mass storage, printing, and other resources to multiple
users.

 Distributed: -A distributed operating system manages a group of distinct computers and makes them
appear to be a single computer. The development of networked computers that could be linked and
communicate with each other gave rise to distributed computing. Distributedcomputations are carried out on
more than one machine. When computers in a group work in cooperation, they form a distributed system.

 Templated:-In an OS, distributed and cloud computing context, templating refers to creating a single
virtual machine image as a guest operating system, then saving it as a tool for multiple running virtual machines.
The technique is used both in virtualization and cloud computing management, and is common in large server
warehouses.

 Embedded: -Embedded operating systems are designed to be used in embedded computer systems.
They are designed to operate on small machines like PDAs with less autonomy. They are able to operate with a
limited number of resources. They are very compact and extremely efficient by design. Windows CE and Minix
3 are some examples of embedded operating systems.

 Real-time: -A real-time operating system is an operating system that guarantees to process events or
data by a specific moment in time. A real-time operating system may be single- or multi- tasking, but when
multitasking, it uses specialized scheduling algorithms so that a deterministic nature of behavior is achieved. An
event-driven system switches between tasks based on their priorities or external events while time-sharing
operating systems switch tasks based on clock interrupts.

 Library: -A library operating system is one in which the services that a typical operating system
provides, such as networking, are provided in the form of libraries and composed with the application and
configuration code to construct a unikernel: a specialized, single address space, machine image that can be
deployed to cloud or embedded environments.

Page | 10
Evolution of Operating Systems: -

 Batch Systems:-In order to improve the utilisation of computing resources, the concept of a batch
operating system was devised. Such an operating system was developed in the mid-1950s by General Motors
for use on IBM mainframes, and was known as the monitor. The operator now batched individual jobs together
sequentially and placed them on an input device. The monitor would load and run one job at a time. On
completion, each job returned control to the monitor, which would then load the next job. Control would also
return to the monitor if an error was encountered. The results of each job were sent to an output device such as a
printer. Because the monitor controlled the sequence of events, part of the program (the resident monitor) had
to residein memory. Other parts of the program were loaded as subroutines at the beginning of any job that
required them.The monitor created some additional system overhead because it occupied a portion of memory
and used the resources of the processor.

 Multiprogramming systems: - In a multiprogramming system, a running application can request an


I/O operation by sending a system call to the operating system. The operating system will issuethe necessary
commands to the I/O device controller, and then initiate or continue the execution of another program.
Multiprogramming systems rely on the generation of interrupts, which are basically signals sent by a hardware
device to inform the processor that it has completed a task (or has encountered an error). On receipt of an interrupt,
the processor passes control back to the operating system, which executes the necessary interrupt-handling
routine. Multiprogramming operating systems require a high degree of sophistication, since they are responsible
for managing memory usage for, and scheduling the execution of, multiple programs.

 Time sharing OS:-In order for the processor's time to be divided fairly between the programs
competing for its use, the operating system interleaves the execution of each program in short time slots. This
process is known as time-sharing, and it prevents one program from hogging the processor to the detriment of
other programs. In a multiprogramming system there is inevitably the possibility that, due to a programming error
for example, one program’s code will attempt to access or overwrite memory that is being used by another
program. In addition to its other duties, therefore, the operating system must also ensure that programs do not
interfere with each other (for example by modifying each other’s program code or data).

 Personal computers:- As early as the 1960s and 1970s, researchers were working on the idea of a
personal computer. Alan Kay, who was working for IBM formulated the idea of a graphical user interface (or
GUI). The interface he envisaged had all of the features we can now see in a modern desktop environment,
including a separate window for each application, a menu-driven application environment, and many other
features now in common use. Then, Apple developed the Macintosh; for the first time, an operating system had
been created that reflected the economic reality that the operator was now a far greater cost factor than the
computer hardware or software. The computer was adapted to suit the operator rather than the other way round.
Almost all operating systems now offer a sophisticated, event-driven, graphical desktop environment designed
primarily for ease of use.

 Parallel Operating Systems:- Parallel operating systems are designed to make efficient use of
computers with multiple processors, and many operating systems currently on the market can take full advantage
of multiple processors if present, providing the application programs they are running have been written using
a programming language that supports multi-threading. The general idea is that different threads of the program
can be executed simultaneously, speeding up the execution of the program as a whole. Programs written for
single-processor computers can often run on a multi-processor system, but can only execute on one processor

Page | 11
at a time.

 Real-time systems:- A real-time operating system is one in which processing activity is triggered by
one or more random external events, each of which will initiate the execution of a predetermined set of
procedures that must be completed within rigid time constraints. Real-time systems are often dedicated to highly
specialized applications, such as flying an aircraft or controlling an industrial process, where an input event
must result in an immediate response. In the early 1980s, real-time systems were used almost exclusively for
applications such as process
control. A process control system typically accepts analogue or digital sensor input, analyses the
data, and takes the appropriate action.

 Distributed systems:- A distributed system is one in which various user resources reside in separate
computer systems connected by a network. The computer systems involved may have diverse hardware and
software platforms, but the user is presented with a uniform computing environment thanks to a distributed
system architecture that provides a standard communications interface. This intermediate layer of software hides
the complexity created by theintercommunication of such diverse technologies. Microsoft's common object
model (COM) was an architecture developed to handle inter-process communication between applications
running onthe same computer. Their distributed common object model (DCOM) architecture is an extension
of COM that enables inter-process communication to take place between applications running on different
computers on a network.

Page | 12
Acropolis Institute of Technology and Research, Indore
Department of CSE (Artificial Intelligence & Machine Learning)
Group / Title:
Lab: Operating System (AL501) Case Studies of File Systems being used in Unix/Linux &
Windows
EVALUATION RECORD Type/ Lab Session:
Name Ansh Dube Enrollment No. 0827Al211016
Performing on First submission Second submission
Extra Regular

Grade and Remarks by the Tutor


1. Clarity about the objective of experiment
2. Clarity about the Outcome
3. Submitted the work in desired format
4. Shown capability to solve the problem
5. Contribution to the team work

Additional remarks

Grade: Cross the grade.


A B C D F

Tutor

1. Title: Case Studies of File Systems being used in Unix/Linux & Windows; System Calls used in these
Operating Systems for file management.
2. Neatly Drawn and labeled experimental setup:

Page | 13
3. Theoretical solution of the instant problem:

UNIX

Unix was initially composed in assembly language. Ken Thompson composed B, for the most part
taking into account BCPL, in view of his involvement in the MULTICS project. B was supplanted by
C, and Unix, revamped in C, formed into a vast, complex group of inter related working frameworks
which have been persuasive in each current operating systems. The Unix-like family is a different
gathering of operating system, with a few noteworthy sub-classifications as well as System V,
BSD, and Linux. The name “UNIX” is a brand name of The Open Group which permits it for use with
any operating system that has been appeared to comply with their definitions.

Linux

The Linux kernels began in 1991, as a venture of Linus Torvalds, while a college understudy in
Finland. He posted data related to his project on newsgroup for PC understudies and developers, and
got support and help from volunteers who achieved something in making a complete and practical
portion. On account of its open license model, the code of Linux kernel is accessible for study and
alteration, which brought about its utilization on an extensive variety of processing hardware from
supercomputers to smart watches.

Windows

Microsoft Windows is a group of exclusive operating system composed by Microsoft Corporation and
essentially focused to Intel design based PCs, with an expected 88.9 percent complete use offer on Web
associated computers. The most recent version is Windows 10.Windows 7 overwhelmed Windows XP
as most basic form in use in 2011.Microsoft Windows was initially released in 1985, as an operating
domain consecutively on peak of MS-DOS, which was standard working framework dispatched on most
Intel engineering PCs at the time.

LINUX VS UNIX VS WINDOWS OPERATING SYSTEM

Introduction:-
 Linux is an illustration of open source programming advancement and free of charge
operating system (OS).
 Unix is a system that is extremely mainstream in colleges, organizations, big enterprises and so
on.
 Microsoft Windows is said as progression of graphical interface system created,
showcased, and traded by Microsoft.
Use:-
 Linux can usually install on a broad range of PC software and hardware, going from
cellular phones, tablets PCs and video game relieves, to centralized servers and supercomputers.
 The Unix system is utilized as a part of web servers, workstations and PCs. It plays an
important role for finance infrastructure and numerous 24×365 high accessibility solutions.
 Windows is a system used on computer’s desktops, portable workstations, servers and
a fewphones.
Users:-
 Linux is an operating system which is used by everybody; from home clients to engineers and
Page | 14
PC lovers alike
 .Unix system were produced fundamentally for servers, mainframes and workstations aside
from OSX, Which is intended for everybody. The Unix setting and the customer server series model
were vital components in the advancement of the Internet.
 Windows is an operating system used by everybody.
Prices:-
 Linux can consider as free operating system, free downloaded, distributed with the help of
books, magazines and so on. There are valued versions for Linux additionally; however they are
typically less expensive as compare to windows.
 Unix have different flavors and also have different price structures as indicated by sellers.
 Windows have usually low price.

System Calls :
A system call is a method for a computer program to request a service from the kernel of
the operating system on which it is running. A system call is a method of interacting with the
operating system via programs. A system call is a request from computer software to an operating
system's kernel.

File management is a system call that is used to handle the files. Some file management examples
include creating files, delete files, open, close, read, write, etc.

Windows: System calls used in windows are :


CreateFile()
ReadFile()
WriteFile()
CloseHandle()

Unix/Linux : System calls used in unix are :


Open()
Read()
Write()
Close()

Page | 15
Acropolis Institute of Technology and Research, Indore
Department of CSE (Artificial Intelligence & Machine Learning)
Group / Title:
Lab: Operating System (AL501) Write a program to implement FCFS CPU Scheduling Algorithm
EVALUATION RECORD Type/ Lab Session:
Name Ansh Dube Enrollment No. 0827Al211016
Performing on First submission Second submission
Extra Regular

Grade and Remarks by the Tutor


1. Clarity about the objective of experiment
2. Clarity about the Outcome
3. Submitted the work in desired format
4. Shown capability to solve the problem
5. Contribution to the team work
Additional remarks

Grade: Cross the grade.


A B C D F

Tutor

1. Title: Write a program to implement FCFS CPU Scheduling Algorithm


2. Theoretical solution of the instant problem :

FCFS, which stands for First-Come-First-Serve, is one of the simplest and most straightforward
scheduling algorithms used in computer operating systems. It is a non-preemptive scheduling technique,
meaning that once a process starts executing, it continues until it completes its execution.
Here's a brief overview of how FCFS works:

Arrival of Processes: When multiple processes are ready to execute, they are placed in a queue based
on the order of their arrival. The process that arrives first is the first to be executed.

Execution: The process at the front of the queue is selected for execution, and it continues to run until it
completes its execution or until it is interrupted by an external event. If a process is not finished, the next
process in the queue is selected for execution.

Completion: The processes are executed in the order they arrived until the queue is empty. The
completion time of each process is determined by the order in which it was placed in the ready queue.

2.1 Algorithm:
Step 1: Input: A set of processes with their burst times
Step 2: Set the current time to 0.
Step 3: Sort The processes on the basis of arrival time
Page | 16
Step 4: Iterate through the sorted list of processes and execute them one by one in the order they
appear in the sorted list.
Step 5: For each process in list
 Set Arrival time of process i (if not started) = max(current time, arrival time of process i)
 Completion time of process i = current time + burst time of process i
 Update current time to the completion time of process i

Step 6: Turnaround time for process i = Completion time of process i - Arrival time of process i
Waiting time for process i = Turnaround time for process i - Burst time of process i
Step 7: Calculate average turnaround time and average waiting time: Sum up the turnaround times
and waiting times and divide by the number of processes to get the averages.
2.2 Program :
#include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
float n,i,j,p[10],q[10],r[10],avgp=0,avgt=0; cout<<"\n\t no. of process(max=10)::"; cin>>n;
for(i=0;i<n;i++)
{
cout<<"\n\t burst time for process "<<i+1<<"::"; cin>>p[i];
} q[0]=0;
for(i=1;i<n;i++)
{
q[i]=q[i-1]+p[i-1];
}
for(i=0;i<n;i++)
{
cout<<"\n\n\t Waiting time for process "<<i+1<<"::"; cout<<q[i];
avgp=avgp+q[i];
}
float s; s=avgp/n;
cout<<" \n\t Average waiting time::"<<s; r[0]=p[0];
for(i=1;i<n+1;i++)
{
r[i]=r[i-1]+p[i];
}

Page | 17
for(i=0;i<n;i++)
{
cout<<"\n\n\t Turn around time for process "<<i+1<<"::"; cout<<r[i];
avgt=avgt+r[i];
}
float l; l=avgt/n;
cout<<" \n\t Average waiting time::"<<l;
getch();
}
3 Tabulation Sheet

INPUT OUTPUT

Enter no. of process(max=10): 3


Burst time for process 1: 5
Burst time for process 2: 3
Burst time for process 3: 6

Page | 18
Acropolis Institute of Technology and Research, Indore
Department of CSE (Artificial Intelligence & Machine Learning)
Group / Title:
Lab: Operating System (AL501)
Write a program to implement SJF CPU Scheduling Algorithm
EVALUATION RECORD Type/ Lab Session:
Name Ansh Dube Enrollment No. 0827Al211016
Performing on First submission Second submission
Extra Regular

Grade and Remarks by the Tutor


1. Clarity about the objective of experiment
2. Clarity about the Outcome
3. Submitted the work in desired format
4. Shown capability to solve the problem
5. Contribution to the team work

Additional remarks

Grade: Cross the grade.


A B C D F

Tutor

1. Title: Write a program to implement SJF CPU Scheduling Algorithm


2. Neatly Drawn and labeled experimental setup

3. Theoretical solution of the instant problem :


Shortest Job First (SJF) is a scheduling algorithm that selects the process with the smallest total
remaining processing time first. There are two variations of SJF: preemptive and non-preemptive.
The key idea behind SJF is to execute the process with the shortest burst time first, minimizing the total
processing time. However, predicting the exact burst time for a process is often challenging in practical
scenarios. In preemptive SJF, the scheduler can interrupt a running process if a new process arrives with
Page | 19
a shorter burst time, allowing for more dynamic adaptation to changing process characteristics.

3.1 Algorithm:
Step 1: Input: A set of processes with their burst times
Step 2: Set the current time to 0.
Step 3: Sort The processes on the basis of arrival time in ascending order.
Step 4: For Each Process
 If the process has not started yet, set its arrival time to the maximum of the current time and the
arrival time of the process.
 Calculate the completion time of the process as the current time plus its burst time.
 Update the current time to the completion time of the process.
 Turnaround time = Completion time - Arrival time
 Waiting time = Turnaround time - Burst time

Step 5: Calculate the average turnround time and waiting time


 Sum up the turnaround times and waiting times.
 Divide the sums by the number of processes to get the averages.

3.2 Program:
#include<iostream.h>
#include<conio.h> int
main()

{
4int i,n,p[20],min,k=1,btime=0;
int
bt[10],temp,j,at[10],wt[10],tt[10],ta=0,sum=0;
float wavg=0,tavg=0,tsum=0,wsum=0;
clrscr();
cout<<"\nEnter the No. of processes
:";cin>>n;

for(i=0;i<n;i++){
5cout<<"\tEnter the burst time of process "<<i+1<<":
";cin>>bt[i];
cout<<"Enter the arrival time of process "<<i+1<<": ";
cin>>at[i];
p[i]=i+1;
}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(at[i]<at[j]){
temp=p[j];
p[j]=p[i];
p[i]=temp;
temp=at[j];
at[j]=at[i];
at[i]=temp;
temp=bt[j];
Page | 20
bt[j]=bt[i];
bt[i]=temp;
}}}
for(j=0;j<n;j++){
btime=btime+bt[j];
min=bt[k];
for(i=k;i<n;i++)

{
6if (btime>=at[i] && bt[i]<min)
{
temp=p[k];
p[k]=p[i];
p[i]=temp;
temp=at[k];
at[k]=at[i];

at[i]=temp;
temp=bt[k];
bt[k]=bt[i];
bt[i]=temp;
}}
k++;
}
wt[0]=0;
for(i=1;i<n;i++){
sum=sum+bt[i-1];
wt[i]=sum-at[i];
wsum=wsum+wt[i];
}
wavg=(wsum/n);
for(i=0;i<n;i++){
ta=ta+bt[i];
tt[i]=ta-at[i];
tsum=tsum+tt[i];
}
tavg=(tsum/n);
cout<<"RESULT - ";
cout<<"\nProcess\t Burst\t Arrival\t Waiting\t Turn-
around"; for(i=0;i<n;i++){

}7 cout<<"\n p"<<p[i]<<"\t "<<bt[i]<<"\t "<<at[i]<<"\t\t"<<wt[i]<<"\t\t"<<tt[i];


cout<<"\n\nAVERAGE WAITING TIME :"<<wavg;
cout<<"\nAVERAGE TURN AROUND TIME:
"<<tavg;
getch();
return 0;}

Page | 21
4. Tabulation Sheet

INPUT OUTPUT

Enter the no. of processes: 4


Enter the burst time of process 1 : 5
Enter the arrival time of process 1 : 0
Enter the burst time of process 2 : 4
Enter the arrival time of process 2 : 2
Enter the burst time of process 3 : 2
Enter the arrival time of process 3 : 2
Enter the burst time of process 4 : 4
Enter the arrival time of process 4 : 4

5. Result:
In this experiment we learnt how to implement SJF CPU Scheduling Algorithm

Page | 22
Acropolis Institute of Technology and Research, Indore
Department of CSE (Artificial Intelligence & Machine Learning)
Group / Title:
Lab: Operating System (AL501) Write a program to implement Priority CPU Scheduling Algorithm.

EVALUATION RECORD Type/ Lab Session:


Name Ansh Dube Enrollment No. 0827Al211016
Performing on First submission Second submission
Extra Regular

Grade and Remarks by the Tutor


1. Clarity about the objective of experiment
2. Clarity about the Outcome
3. Submitted the work in desired format
4. Shown capability to solve the problem
5. Contribution to the team work

Additional remarks

Grade: Cross the grade.


A B C D F

Tutor

1. Title: Write a program to implement Priority CPU Scheduling Algor


2. Theoretical solution of the instant problem
Priority scheduling is a CPU scheduling algorithm that assigns priority levels to each process and then
selects the process with the highest priority for execution.

Priority scheduling aims to give preference to processes with higher priority, but it may suffer from the
"starvation" problem if lower-priority processes are continually pushed down the queue. In some
variations, aging mechanisms may be introduced to gradually increase the priority of waiting processes
to prevent starvation.

In a preemptive priority scheduling, the priority of a running process can be changed dynamically if a
process with a higher priority arrives. In a non-preemptive version, the priority is fixed once a process
starts its execution.

2.1 Algorithm:
Step 1: Input: A set of processes with their burst times
Step 2: Set the current time to 0.
Step 3: Sort The processes on the basis of arrival time in ascending order.

Page | 23
Step 4: Assign Priority Levels: Higher priority values typically indicate higher priority. If multiple
processes have the same priority, you might use another criterion, such as arrival time, to break ties.
Step 5: For Each Process
 If the process has not started yet, set its arrival time to the maximum of the current time and the
arrival time of the process.
 Calculate the completion time of the process as the current time plus its burst time.
 Update the current time to the completion time of the process.
 Turnaround time = Completion time - Arrival time
 Waiting time = Turnaround time - Burst time

Step 6: Calculate the average turnround time and waiting time


 Sum up the turnaround times and waiting times.
 Divide the sums by the number of processes to get the averages.

2.2 Program:
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{int et[20],at[10],n,i,j,temp,p[10],st[10],ft[10],wt[10],ta[10],
totwt=0,totta=0; float awt,ata; char pn[10][10],t[10];

clrscr(); the number of process:";


3cout<<"Enter
cin>>n;
for(i=0; i<n; i++)
{cout<<"Enter process id,arrivaltime,execution time & priority:";
cin>>pn[i]>>at[i]>>et[i]>>p[i]; }
for(i=0; i<n; i++)
for(j=0; j<n; j++)
{if(p[i]<p[j])
{temp=p[i];
p[i]=p[j]; p[j]=temp; temp=at[i]; at[i]=at[j];
at[j]=temp; temp=et[i];
et[i]=et[j]; et[j]=temp;
strcpy(t,pn[i]);

strcpy(pn[i],pn[j]);
4strcpy(pn[j],t)
}
}for(i=0; i<n; i++)
{if(i==0)
{st[i]=at[i];
wt[i]=st[i]-at[i];
ft[i]=st[i]+et[i];
ta[i]=ft[i]-at[i];} else
{ st[i]=ft[i-1];
wt[i]=st[i]-at[i];
ft[i]=st[i]+et[i];
Page | 24
ta[i]=ft[i]-at[i];}
totwt+=wt[i];
totta+=ta[i]; }
awt=(float)totwt/n
;ata=(float)totta/n;
cout<<"\nPname\tarrivaltime\texecutiontime\tpriority\twaitingtime\ttati
me"; for(i=0; i<n; i++)
cout<<"\n"<<pn[i]<<"\t"<<at[i]<<"\t\t"<<et[i]<<"\t\t"<<p[i]<<"\t\t"<<wt[i]<<"\t\t"<<ta[i];
cout<<"\nAverage waiting time is: "<<awt;
cout<<"\nAverage turn around time
is"<<ata;
getch();

4. Tabulation Sheet

INPUT OUTPUT

Enter the no. of process : 3


Enter the process id, arrival time, execution
time & priority : 1
0
3
1
Enter the process id, arrival time, execution
time & priority : 2
3
4
2
Enter the process id, arrival time, execution
time & priority : 3
4
2
3

5. Result:
In this experiment we learnt how to implement Pirority CPU Scheduling Algorithm

Page | 25
Acropolis Institute of Technology and Research, Indore
Department of CSE (Artificial Intelligence & Machine Learning)
Group / Title:
Lab: Operating System (AL501) Write a program to implement Round Robin CPU Scheduling
Algorithm
EVALUATION RECORD Type/ Lab Session:
Name Ansh Dube Enrollment No. 0827Al211016
Performing on First submission Second submission
Extra Regular

Grade and Remarks by the Tutor


1. Clarity about the objective of experiment
2. Clarity about the Outcome
3. Submitted the work in desired format
4. Shown capability to solve the problem
5. Contribution to the team work

Additional remarks

Grade: Cross the grade.


A B C D F

Tutor

1. Title: Write a program to implement Round Robin CPU Scheduling Algorithm


2. Neatly Drawn and labeled experimental setup:

Page | 26
3. Theoretical solution of the instant problem:
Round Robin is a simple and widely used CPU scheduling algorithm in operating systems. It is a
preemptive scheduling algorithm that assigns a fixed time unit (time quantum or time slice) to each
process in the system.

Round Robin is easy to understand and implement, and it ensures fairness by giving each process an
equal share of the CPU. However, it may lead to high turnaround times and waiting times for certain
scenarios, especially if the time quantum is too large. The choice of an appropriate time quantum is
crucial for optimizing the performance of the Round Robin scheduling algorithm.
3.1 Algorithm:
Step 1: Input: A set of processes with their burst times
Step 2: Set the current time to 0.
Step 3: Sort The processes on the basis of arrival time in ascending order.
Step 4: Create a Ready Queue: Place all processes in a ready queue.
Step 5: For Each Process
 If the process has not started yet, set its arrival time to the maximum of the current time and the
arrival time of the process.
 Execute the process for the specified time quantum.
 If the process completes within the time quantum, calculate its completion time and move to the
next process.
 If the process does not complete within the time quantum, move it to the end of the ready queue
to wait for the next turn.
 Update the current time to the completion time of the process.
 Turnaround time = Completion time - Arrival time
 Waiting time = Turnaround time - Burst time

Step 6: Calculate the average turnround time and waiting time


 Sum up the turnaround times and waiting times.
 Divide the sums by the number of processes to get the averages.

3.2 Program:
#includeostream.h>
#include<conio.h>
int main()
{int count,j,n,time,remain,flag=0,time_quantum;
int wait_time=0,turnaround_time=0,at[10],bt[10],rt[10];
cout<<"Enter Total Process:\t ";
cin>>n;
remain=n;
for(count=0;count<n;count++)
{ cout<<"Enter Arrival Time and Burst Time for Process Process Number "<<count+1<<": ";
cin>>at[count];
cin>>bt[count]; rt[count]=bt[count];
}
cout<<"Enter Time Quantum:\t";
Page | 27
cin>>time_quantum;
cout<<"\n\nProcess\t|Turnaround Time|Waiting Time\n\n";
for(time=0,count=0;remain!=0;)
{
if(rt[count]<=time_quantum && rt[count]>0)
{
time+=rt[count];
rt[count]=0; flag=1; }
else if(rt[count]>0)
{
rt[count]-=time_quantum; time+=time_quantum;
}
if(rt[count]==0 && flag==1)
{
remain--;
cout<<"P["<<count+1<<"]\t|\t"<<time-at[count]<<"\t|\t"<<time-at[count]-bt[count]<<"\n";
wait_time+=time-at[count]-bt[count];
turnaround_time+=time-at[count]; flag=0;
}
if(count==n-1) count=0;
else if(at[count+1]<=time) count++;
else
count=0; }
cout<<"\nAverage Waiting Time= "<<wait_time*1.0/n<<"\n";
cout<<"Avg Turnaround Time = "<<turnaround_time*1.0/n;
getch();
return 0;
}

4 Tabulation Sheet

INPUT OUTPUT

Enter Total Process: 3


Enter Arrival Time and Burst Time for
Process Number 1: 0
2
Enter Arrival Time and Burst Time for
Process Number 2:1
3
Enter Arrival Time and Burst Time for
Process Number 3: 2
2
Enter time quantum: 2

5. Result:
In this experiment we learnt how to implement Round Robin CPU Scheduling Algorithm

Page | 28
Page | 29
Acropolis Institute of Technology and Research, Indore
Department of CSE (Artificial Intelligence & Machine Learning)
Group / Title:
Lab: Operating System (AL501)
Write a program to implement Banker’s Algorithms.
EVALUATION RECORD Type/ Lab Session:
Name Ansh Dube Enrollment No. 0827Al211016
Performing on First submission Second submission
Extra Regular

Grade and Remarks by the Tutor


1. Clarity about the objective of experiment
2. Clarity about the Outcome
3. Submitted the work in desired format
4. Shown capability to solve the problem
5. Contribution to the team work

Additional remarks

Grade: Cross the grade.


A B C D F

Tutor

1. Title: Write a program to implement Banker’s Algorithms.


2. Neatly Drawn and labeled experimental setup
3. Theoretical solution of the instant problem:
The Banker's Algorithm is a resource allocation and deadlock avoidance algorithm used in operating
systems. It is designed to ensure that a system will not enter an unsafe state, where processes are
deadlocked, by carefully managing the allocation of resources.

The Banker's Algorithm ensures that the system remains in a safe state by only granting a resource
request if it satisfies the safety criteria. This helps prevent deadlock situations where processes are
waiting indefinitely for resources. It is commonly used in systems with multiple processes and
resources, such as in multitasking operating systems.
3.1 Algorithm:
Step 1: Input : Information about the total number of resources in the system and the maximum demand
of each process for each resource.
Step 2: Create data structures to store information about allocated, maximum, and need resources for
each process. Set the Work vector equal to the available resources, and initialize the Finish array to all
false.
Step 3: Safety Check:
 Repeat the following until all processes finish or an unsafe state is detected:
 Iterate through each process.
 If the process has not finished and its resource needs can be satisfied with the current available
resources:
Page | 30
 Simulate the allocation of resources to the process.
 Update the Work vector.
 Mark the process as finished.
Step 4: Resource Request:
 When a process requests additional resources, check if the request can be granted without
entering an unsafe state.
 If the request is granted, update the allocation and need matrices.
 Release the allocated resources when the process finishes.
Step 5: Print the results, including whether the system is in a safe state and the final state of the
allocation and need matrices.

3.2 Program:

#include<iostream.h>
#include<conio.h>
void main()
{ int
alloc[10][10],max[10][10],avail[10],n,m,need[10][10],i,j,k;
clrscr();
cout<<"Enter no. of processes :: ";
cin>>n;
cout<<"Enter no. of resources :: ";
cin>>m;
// cout<<"Enter allocation matrix:";
for(i=0;i<n;i++)
{ for(j=0;j<m;j++)
{ cout<<"\nEnter no. of instances of "<<j+1<<"allocated to "<<i+1<<"::
" ;cin>>alloc[i][j];

}// }cout<<"\nEnter max matrix";


for(i=0;i<n;i++)

{{ for(j=0;j<m;j++)
cout<<"\nEnter maximum instances of"<<j+1<<"allocated to "<<i+1<<":: ";
cin>>max[i][j];

}}
for(i=0;i<m;i++)
{ cout<<"\nEnter available instances of "<<i+1<<"::
";cin>>avail[i];

}//calculate need matrix


for(i=0;i<n;i++)
{ for(j=0;j<m;j++)
{ need[i][j]=max[i][j]-alloc[i][j];
}}
cout<<"\nAllocation matrix is:\n";
for(i=0;i<n;i++)
{ for(j=0;j<m;j++)
{ cout<<alloc[i][j]<<"\t";
}

Page | 31
cout<<endl;
}
cout<<"\nMax matrix is:\n";
for(i=0;i<n;i++)
{ for(j=0;j<m;j++)

{ cout<<max[i][j]<<"\t";
}
cout<<endl;
}
cout<<"\nNeed matrix is:\n";
for(i=0;i<n;i++)
{ for(j=0;j<m;j++)
{
cout<<need[i][j]<<"\t";
}
cout<<endl;
}
int temp=0,p=0;
for( ; p<n;p++)
{ for(i=0;i<n;i++)
{ for(j=0;j<m;j++)
{ if(need[i][j]<=avail[j])
{ temp=1;
}
else
{ temp=0;
break;
}}
if(temp==1)
{ cout<<"\t p"<<i+1;
p++;

for(k=0;k<m;k++)
{ avail[k]+=need[i][k];
need[i][k]=100;
}}}}
getch();
}

Page | 32
4 Tabulation Sheet

INPUT OUTPUT

Enter no. of process: 5


Enter no. of resources: 3

Enter no. of instances of 1 allocated to 1: 0


Enter no. of instances of 2 allocated to 1: 1
Enter no. of instances of 3 allocated to 1: 0
Enter no. of instances of 1 allocated to 2: 2
Enter no. of instances of 2 allocated to 2: 0
Enter no. of instances of 3 allocated to 2: 0
Enter no. of instances of 1 allocated to 3: 3
Enter no. of instances of 2 allocated to 3: 0
Enter no. of instances of 3 allocated to 3: 2
Enter no. of instances of 1 allocated to 4: 2
Enter no. of instances of 2 allocated to 4: 1
Enter maximum of instances of 1 allocated to 1:7
Enter maximum of instances of 1 allocated to 1:5
Enter maximum of instances of 1 allocated to 1:3
Enter maximum of instances of 1 allocated to 2:3
Enter maximum of instances of 1 allocated to 2:2
Enter maximum of instances of 1 allocated to 2:2
Enter maximum of instances of 1 allocated to 3:9
Enter maximum of instances of 1 allocated to 3:0
Enter maximum of instances of 1 allocated to 3:2
Enter maximum of instances of 1 allocated to 4:2
Enter maximum of instances of 1 allocated to 4:2
Enter maximum of instances of 1 allocated to 4:2
Enter available instances of 2: 3
Enter available instances of 3: 2

5. Result:
In this experiment we learnt how to implement Banker’s Algorithm

Page | 33
Acropolis Institute of Technology and Research, Indore
Department of CSE (Artificial Intelligence & Machine Learning)
Group / Title:
Lab: Operating System (AL501)
Write a program to simulate Memory Allocation Strategies
EVALUATION RECORD Type/ Lab Session:
Name Ansh Dube Enrollment No. 0827AL2111047
Performing on First submission Second submission
Extra Regular

Grade and Remarks by the Tutor


1. Clarity about the objective of experiment
2. Clarity about the Outcome
3. Submitted the work in desired format
4. Shown capability to solve the problem
5. Contribution to the team work

Additional remarks

Grade: Cross the grade.


A B C D F

Tutor

1.Title: Write a program to simulate Memory Allocation Strategies (First fit, Best fit and Worst fit).
2. Theoretical solution of the instant problem:

Memory allocation strategies refer to the methods used by operating systems to assign memory blocks to
processes. Here are three common memory allocation strategies: First Fit, Best Fit, and Worst Fit.

 First Fit: In the First Fit strategy, the operating system allocates the first available block of
memory that is large enough to accommodate the process. It starts searching from the beginning
of the available memory and selects the first block that is equal to or larger than the size of the
process. This method is simple and easy to implement but may lead to fragmentation over time,
as it may leave small, unusable gaps between allocated blocks.
 Best Fit: The Best Fit strategy aims to minimize wasted memory by allocating the smallest
available block that is still large enough to accommodate the process. The operating system
searches the entire list of available memory blocks and selects the one that results in the least
amount of wasted space after allocation. While Best Fit can help reduce fragmentation, it may
lead to more frequent searches and slightly higher overhead compared to First Fit.
 Worst Fit: The Worst Fit strategy allocates the largest available block of memory to the process.
The operating system searches for the largest available memory block and assigns it to the
process, leaving behind a larger fragment. While Worst Fit may seem counterintuitive, it is based
on the idea that larger fragments are more likely to accommodate future processes. However, it
can result in inefficient use of memory due to increased fragmentatio
2.1 Program:
#include<iostream.h>
#include<conio.h>
Page | 34
void first();
void best();
void worst();

void main()
{
int choice;
clrscr(); do

{clrscr();
cout<<"\nThis is the program for performing different menory allocation strategies:"<<endl;
cout<<"1. First fit \n2. Best fit\n3. Worst fit"<<endl;
cout<<"Press 0 to exit:-)"<<endl; cout<<"Please
enter your choice:"<<endl; cin>>choice;

switch(choice)
{
case 1:
first();
break; case 2:

break; case 3: best();

break; default:
worst();
cout<<"Invalid input: Please try again"<<endl;
}
}
while(choice!=0);
}

void first()
{
clrscr();
int bsize[10], psize[10], bno, pno, flags[10], allocation[10], i, j; for(i =
0; i < 10; i++)
{

Page | 35
flags[i] = 0;
allocation[i] = -1;
}
cout<<"Enter no. of blocks: ";
cin>>bno;
cout<<"\nEnter size of each block: "; for(i
= 0; i < bno; i++)

cin>>bsize[i];
cout<<"\nEnter no. of processes: ";
cin>>pno;
cout<<"\nEnter size of each process: "; for(i
= 0; i < pno; i++)
cin>>psize[i];
for(i = 0; i < pno; i++) //allocation as per first
fit for(j = 0; j < bno; j++)
if(flags[j]
{ ==allocation[j]
0 && bsize[j]
= >= psize[i])
i; flags[j] = 1;
break; }
//display allocation details
cout<<"\nBlock no.\tsize\t\tprocess no.\t\tsize"; for(i
= 0; i < bno; i++)
{
cout<<"\n"<< i+1<<"\t\t"<<bsize[i]<<"\t\t";
if(flags[i] == 1)

cout<<allocation[i]+1<<"\t\t\t"<<psize[allocation[i]];
else
cout<<"Not allocated";
}
getch();
}

void best()
{
clrscr():
int fragment[20],b[20],p[20],i,j,nb,np,temp,lowest=9999;
static int barray[20],parray[20];
cout<<"\n\t\t\tMemory Management Scheme - Best Fit";
cout<<"\nEnter the number of blocks:";

cin>>nb;
cout<<"Enter the number of processes:";
cin>>np;
cout<<"\nEnter the size of the blocks:-\n";
for(i=1;i<=nb;i++)
{
cout<<"Block no."<<i<<":";
cin>>b[i];

}cout<<"\nEnter the size of the processes :-\n";


Page | 36
for(i=1;i<=np;i++)

{
cout<<"Process no. "<<i<<":";
cin>>p[i];

}for(i=1;i<=np;i++)
{
for(j=1;j<=nb;j++)
{
if(barray[j]!=1)
{
temp=b[j]-p[i]; if(temp>=0)
if(lowest>temp)

{parray[i]=j; lowest=temp;
}
}
}
fragment[i]=lowest;
barray[parray[i]]=1;
lowest=10000;
}
cout<<"\nProcess_no\tProcess_size\tBlock_no\tBlock_size\tFragment
"; for(i=1;i<=np && parray[i]!=0;i++)
cout<<"\n"<<i<<"\t\t"<<p[i]<<"\t\t"<<parray[i]<<"\t\t"<<b[parray[i]]<<"\t\t"<<fragment[i];
getch();

}
void worst()
{
clrscr();
int nBlocks,nProcess,blockSize[20],processSize[20]; cout<<"
Enter the number of blocks: "; cin>>nBlocks; cout<<" Enter
the number of processes: "; cin>>nProcess; cout<<" Enter the
size of "<<nBlocks<<" blocks: "; for(int i=0;i<nBlocks;i++)

cin>>blockSize[i];
cout<<" Enter the size of "<<nProcess<<" processes: ";
for(i=0;i<nProcess;i++)
cin>>processSize[i];
for(i=0;i<nProcess;i++)
{ int max = blockSize[0]; int pos
= 0;
for(int j=0;j<nBlocks;j++) if(max
< blockSize[j])

{max = blockSize[j]; pos = j;


}
if(max >= processSize[i])

Page | 37
{

cout<<"\nProcess "<<i+1<<" is allocated to block "<<pos+1;


blockSize[pos] = blockSize[pos]-processSize[i];
}
else
{
cout<<"\nProcess "<<i+1<<" can't be allocated";
}
}
getch();
}

4. Output:

First fit

Page | 38
Best fit

Page | 39
Acropolis Institute of Technology and Research, Indore
Department of CSE (Artificial Intelligence & Machine Learning)
Group / Title:
Lab: Operating System (AL501) Write a program to implement various Page Replacement
Algorithms
EVALUATION RECORD Type/ Lab Session:
Name Ansh Dube Enrollment No. 0827Al211016
Performing on First submission Second submission
Extra Regular

Grade and Remarks by the Tutor


1. Clarity about the objective of experiment
2. Clarity about the Outcome
3. Submitted the work in desired format
4. Shown capability to solve the problem
5. Contribution to the team work

Additional remarks

Grade: Cross the grade.


A B C D F

Tutor

1. Title: Write a program to implement various Page Replacement Algorithms


2. Theoretical solution of the instant problem:
Page replacement algorithms are used in operating systems to manage the contents of the page table
when a page fault occurs, and the required page is not in memory.

 Optimal Page Replacement (OPT or MIN): In the Optimal algorithm, the page that will not be
used for the longest period in the future is selected for replacement. This algorithm provides the
lowest page-fault rate but is practically impossible to implement because it requires knowledge
of future page references.

 LRU (Least Recently Used): LRU replaces the page that has not been used for the longest
period. It requires maintaining a record of the order in which pages are accessed, and the least
recently used page is chosen for replacement. Implementing a true LRU algorithm can be
complex, and approximation methods like the clock algorithm are often used.
 FIFO (First-In-First-Out): The FIFO algorithm replaces the oldest page in memory. It uses a
queue data structure to keep track of the order in which pages are brought into memory. While
easy to implement, FIFO may suffer from the "Belady's anomaly," where increasing the number
of page frames can increase the page-fault rate.

Page | 40
3.1 Program:

#include<iostream.h>
#include<conio.h>

void fcfs(); void


optimal(); void
lru();

int n,page[20],f,fr[20],i;

void main()
{
int choice;
clrscr(); do

{clrscr();
cout<<"\nThis is the program for performing different page replacement algorithms:"<<endl;
cout<<"1. FCFS \n2. Optimal page replacement\n3. LRU"<<endl;
cout<<"Press 0 to exit:-)"<<endl; cout<<"Please
enter your choice:"<<endl; cin>>choice;
switch(choice)
{
case 1:
fcfs();
break;
case 2:
optimal();
break;
case 3:
lru();
break; default:

int getReplaceposition(int counter[],int n)


{
int max = counter[0]; int
pos=0;

Page | 41
for(int i=0;i<n;i++)
{
if(counter[i]>max)
{
pos=i;
max = counter[i];
}
}
return pos;
}

void fcfs()
{
clrscr();
int pages[20],i,frames[10],counter[10]; int
nPages,nFrames,pageFault=0; clrscr();
cout<<"Enter the number of pages(MAX 20): "; cin>>nPages;
cout<<"Enter the number of frames(MAX 10): "; cin>>nFrames;
cout<<"Enter the Page reference string: ";
for(i=0;i<nPages;i++)
{
cin>>pages[i];
}
for(i=0;i<nFrames;i++)
{
frames[i] = 0;
counter[i] = 0; //here 0 referes an empty space in frame
}

for(i=0;i<nPages;i++)
{
int flag =0;
for(int j=0;j<nFrames;j++)
{
if(frames[j] == pages[i])
{
flag=1; //if page is present in frame (flag=1)
break;
}
}
//if page is not present in frame (flag=0)
if(flag == 0)
pageFault++;
for(int j=0;j<nFrames;j++)
{
if(frames[j] == 0)
{
frames[j] = pages[i];
Page | 42
flag=1; counter[j]++;
break;
}
}
}
//if there is no empty frame if(flag
== 0)
{
int pos = getReplaceposition(counter,nFrames);
frames[pos] = pages[i];

counter[pos]
for(int = 1;
k=0;k<nFrames;k++)
{
if(k!=pos)
counter[k]++;
}
}
cout<<endl; for(j=0;j<nFrames;j++)
{
cout<<frames[j]<<" ";
}
}
cout<<"\nPage Fault: "<<pageFault;
getch();

void display()
{
for(i=0;i<f;i++)
{
cout<<fr[i];
}
cout<<"\n";
}

void request()
{
cout<<"enter no.of pages:";
cin>>n;
cout<<"enter no.of frames:";
cin>>f;
cout<<"enter no.of page no.";
for(i=0;i<n;i++)
Page | 43
{
cin>>page[i];
}
for(i=0;i<n;i++)
{
fr[i]=-1;
}
}

void replace()
{
int j,flag=0,pf=0;
int max,lp[10],index,m;
for(j=0;j<f;j++)

{fr[j]=page[j];
flag=1; pf++;
display();
}
for(j=f;j<n;j++)
{
flag=0;
for(i=0;i<f;i++)

{if(fr[i]==page[j])
{
flag=1;break;

}}
if(flag==0)
{
for(i=0;i<f;i++)
lp[i]=0;
for(i=0;i<f;i++)

{for(m=j+1;m<n;m++)
{
if(fr[i]==page[m])
{
lp[i]=m-j; break;

}}
}
max=lp[0];
index=0;
for(i=0;i<f;i++)

Page | 44
if(lp[i]==0)
{
index=i; break;

}else
{
if(max<lp[i])
{
max=lp[i]; index=i;

}} }
fr[index]=page[j];
pf++;

display();
}
}
cout<<"page faults:"<<pf;
}

void optimal()
{
clrscr();
request();
replace();
getch();

int min(int counter[],int nFrames)


{
int minimum = counter[0]; int
pos;
for(int i=0;i<nFrames;i++) { if(minimum > counter[i]) pos =
i;
}
return pos;
}

void lru()
{
clrscr();
int pageString[50],n,frames[10],counter[10],recent = 0; int
pageFault = 0,nFrames;
clrscr();
cout<<"Enter the number of pages: "; cin>>n;
cout<<"Enter the page reference string: "; for(int
i=0;i<n;i++) cin>>pageString[i];
Page | 45
frames[i]
counter[i]==0;0;//here 0 referes an empty space in frame
}
for(i=0;i<n;i++)
{int flag =0;
for(int j=0;j<nFrames;j++)
{
if(frames[j] == pageString[i])
{flag=1;
counter[j] = recent++; break;
}
}
if(flag == 0)
{

for(int j=0;j<nFrames;j++)
{if(frames[j]
{ frames[j] = == 0)
pageString[i]; counter[j]
= recent++; flag=1;
pageFault++; break;
}

}
}
if(flag == 0){
int PositionToreplace = min(counter,nFrames);
frames[PositionToreplace] = pageString[i];
counter[PositionToreplace] = recent++;
pageFault++;

}
//print frames
cout<<endl; for(j=0;j<nFrames;j++)
{
cout<<frames[j]<<" ";
}

}
cout<<"\nPage Fault: "<<pageFault;
getch();

Page | 46
4. Outputs:

FCFS

Page | 47
Optimal

LRU:

Page | 48
Acropolis Institute of Technology and Research, Indore
Department of CSE (Artificial Intelligence & Machine Learning)
Group / Title:
Lab: Operating System (AL501) Write a program to implement various Disk Scheduling
Algorithms.
EVALUATION RECORD Type/ Lab Session:
Name Ansh Dube Enrollment No. 0827Al211016
Performing on First submission Second submission
Extra Regular

Grade and Remarks by the Tutor


1. Clarity about the objective of experiment
2. Clarity about the Outcome
3. Submitted the work in desired format
4. Shown capability to solve the problem
5. Contribution to the team work

Additional remarks

Grade: Cross the grade.


A B C D F

Tutor

1. Title: Write a program to implement various Disk Scheduling Algorithms.


2. Theoretical solution of the instant problem:
Disk scheduling algorithms are used in operating systems to determine the order in which requests for
disk I/O are serviced.
 First-Come-First-Serve (FCFS): Requests are serviced in the order they arrive in the disk queue.
Simple and easy to implement, but it may lead to the "elevator" or "head-of-line" problem, where
the disk arm moves back and forth excessively.

 Shortest Seek Time First (SSTF): The request with the shortest seek time (distance between
current position and requested track) is serviced first. Aims to minimize the movement of the
disk arm, providing better response time, but may lead to starvation of some requests.
 Scan (Elevator) Algorithm: The disk arm starts at one end of the disk and moves towards the
other end, servicing requests along the way. When it reaches the end, it reverses direction. This
pattern continues until all requests are serviced. Helps in reducing the "starvation" problem but
can still lead to suboptimal performance for certain workloads.
2.1 Program:
#include<stdio.h>

#include<math.h>

{ int i,s=0;
Page | 49
for(i=0;i<noq;i++)

{ s=s+abs(st-qu[i]);

st=qu[i];

printf("\n Total seek time :%d",s);

void sstf(int noq, int qu[10], int st, int visit[10])

{ int min,s=0,p,i;

while(1)

{ min=999;

for(i=0;i<noq;i++) if

(visit[i] == 0)

{ if(min > abs(st - qu[i]))


{ min = abs(st-qu[i]);p =

i;

}}
if(min == 999)

break;

visit[p]=1; s=s

+ min;

st = qu[p];

Page | 50
}

printf("\n Total seek time is: %d",s);

void scan(int noq, int qu[10], int st, int ch)

{ int i,j,s=0;

for(i=0;i<noq;i++)

{ if(st < qu[i])


{

for(j=i-1; j>= 0;j--)

{ s=s+abs(st - qu[j]);st

= qu[j];

}
if(ch == 3)

{ s = s + abs(st - 0);st

= 0; }

for(j = 1;j < noq;j++)


{ s= s + abs(st - qu[j]);st

= qu[j];

break; }

printf("\n Total seek time : %d",s);

int main()

{ int n,qu[20],st,i,j,t,noq,ch,visit[20];

printf("\n Enter the maximum number of cylinders :

");scanf("%d",&n);
Page | 51
printf("enter number of queue

elements");scanf("%d",&noq);

printf("\n Enter the work

queue"); for(i=0;i<noq;i++)

{ scanf("%d",&qu[i]);

visit[i] = 0;

printf("\n Enter the disk head starting posision:

\n");scanf("%d",&st);

{ printf("\n\n\t\t MENU \n");

printf("\n\n\t\t 1. FCFS \n");

printf("\n\n\t\t 2. SSTF \n");

printf("\n\n\t\t 3. SCAN \n");

printf("\n\n\t\t 4. EXIT \n");

printf("\nEnter your choice:

");scanf("%d",&ch);

{ for(i=0;i<noq;i++)

for(j=i+1;j<noq;j++)

if(qu[i]>qu[j])

{ t=qu[i];
qu[i] = qu[j];

qu[j] = t;

}}
switch(ch)

Page | 52
case 1: printf("\n FCFS

\n");

printf("\n*****\n");

fcfs(noq,qu,st)

case 2: printf("\n

SSTF \n");

printf("\n*****\n");

sstf(noq,qu,st,visit);

break;

case 3: printf("\n

SCAN \n");

printf("\n*****\n");

scan(noq,qu,st,ch);

break

}}}

3 Tabulation Sheet

INPUT OUTPUT

Enter the maximum number of cylinders: Enter Your Choice: 1


200 enter number of queue elements 5
Enter the work queue 23 FCFS
89 *****
132 Total seek time: 421
42 MENU
187 1.FCFS
Enter the disk head starting position: 100 2.SSTF
MENU 3. SCAN
1. FCFS 4. EXIT
2. SSTF Enter Your Choice: 2
3. SCAN
SSTF
4. EXIT *****
Enter Your Choice: Total seek time is: 273
MENU
1.FCFS
2.SSTF
3. SCAN
4. EXIT
Enter your choice: 3
SCAN
*****
Total seek time: 287
MENU
1. FCFS
2. SSTF
3. SCAN
EXIT Enter your choice: 4

Page 54

You might also like