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

Operating Systems Manual - BCS303

Uploaded by

M K DHANANJAYA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Operating Systems Manual - BCS303

Uploaded by

M K DHANANJAYA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

VISVESVARAYA TECHNOLOGICAL UNIVERSITY

Belgaum, Karnataka-590 014

OPERATING SYSTEMS LABORATORY


Subject Code: BCS303
(As per Visvesvaraya Technological University Syllabus)

B.E- 3rd Semester, Information Science and Engineering


Prepared By

Prof. Dhananjaya M K
Assistant Professor

Reviewed By
Dr.Lokanna Kadakolmath

Approved By
Prof. Kala Venugopal
Head of Department Information Science and Engineering

ACHARYA INSTITUTE OF TECHNOLOGY


(Affiliated to VTU, Belgaum, Approved by AICTE, New Delhi and Govt. of Karnataka),
Acharya Dr. Sarvepalli Radhakrishnan Road, Bangalore-560107.
Ph: 91-080-28396011, 23723466, 28376431
URL: www.acharya.ac.in
2023-24
Table of contents
Vision, Mission, Motto of Institute I
Vision, Mission of Department II
Laboratory Objectives III
Program Specific Outcomes (PSOs) III
Program outcomes (POs) IV
Course outcomes (COs) VI
MOTTO

"Nurturing Aspirations Supporting Growth" VISION “Acharya Institute of Technology,


committed to the cause of sustainable value-based education in all disciplines, envisions
itself as a global fountainhead of innovative human enterprise, with inspirational initiatives
for Academic Excellence”.

VISION OF THE INSTITUTE

Acharya Institute of Technology, committed to the cause of value-based education in all


disciplines, envisions itself as fountainhead of innovative human enterprise, with
inspirational initiatives for Academic Excellence.

MISSION OF INSTITUTE

“Acharya Institute of Technology strives to provide excellent academic ambiance to the students
for achieving global standards of technical education, foster intellectual and personal development,
meaningful research and ethical service to sustainable societal needs.”
VISION OF THE DEPARTMENT

“To be center of Academic and Research excellence in the field of Information Technology
inculcating value based education for the development of quality Human Resource”

MISSION OF THE DEPARTMENT

“Equip students with fundamental concepts, practical knowledge and professional ethics through
dedicated faculty for higher studies and professional career in various Scientific, Engineering and
Technological streams leading to proficiency in the field of Information Technology”
PROGRAM SPECIFIC OUTCOMES (PSOs)

PSO1: Able to apply knowledge of information management and communication systems to provide secured
solutions for real time engineering applications.
PSO2: Apply best software engineering practices, modern tools and technologies to deliver quality products.

PROGRAM OUTCOMES (Pos)


Engineering Graduates will be able to:
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and an
engineering specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering problems
reaching substantiated conclusions using first principles of mathematics, natural sciences, and engineering
sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and design system
components or processes that meet the specified needs with appropriate consideration for the public health and
safety, and the cultural, societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to provide
valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering and
IT tools including prediction and modeling to complex engineering activities with an understanding of the
limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal, health,
safety, legal and cultural issues and the consequent responsibilities relevant to the professional engineering
practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions in societal
and environmental contexts, and demonstrate the knowledge of, and need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and design
documentation, make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a member and leader in a team, to manage projects
and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in independent
and life-long learning in the broadest context of technological change.

Course Outcomes-Program Outcomes mapping

Program Outcomes Program Specific


COs Outcomes
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PSO1 PSO2
CO-1
CO-2

Rubrics for assessing student’s performance in Laboratory courses

The internals marks of lab for 2022 scheme is 15 Marks for Continuous Evaluation and 10 Marks for Lab Internals.
Continuous Evaluation for 2022 scheme:

Sl Parameters Mark 5 4 3 0
No
1. Writing Program/Logic 10 The student is The student is The student has The student is
(present able to write able to write the written not attempted
week’s/previous the program program with incomplete to write
week’s) without any minor logical program with program.
logical and error major logical
syntactical and syntactical
error and error
proper
indentation is
followed.
2. Implementation in the 10 Student is able Student is able Student is The student
target language with to execute, to execute the executed the has not
different inputs debug, and test program, but program executed the
the program for fails to debug, partially(fails to program.
all possible and test the meet desired
inputs/test program for all output)
cases. possible
inputs/test
cases.
Parameters 6 4 2 0 6
3. Record 6 Student Student submits Student fails to The student
submits the the record on submit the does not
record on time time but not record on time. submit the
and, neatly documented record.
documented properly with all
with all possible
possible input/output
input/output samples.
samples.

Parameters 4 4 2 1 0

4. Viva 4 Student Student answers Student Student fails


answers for at for at least 60% answers for at to answer any
least 80% of of questions least 40% of question
questions questions
5. Internal Assessment 20
Programming Assignments

SL. Name of Program Page


NO No
1 Develop a c program to implement the Process system calls (fork (), 17-19
exec(), wait(), create process, terminate process)
2 20-27
Simulate the following CPU scheduling algorithms to find turnaround
time and waiting time a) FCFS b) SJF c) Round Robin d) Priority.
3 Develop a C program to simulate producer-consumer problem using 28-31
semaphores.
4 Develop a C program which demonstrates interprocess communication 32-33
between a reader process and a writer process. Use mkfifo, open, read,
write and close APIs in your program.
5 34-37
Develop a C program to simulate Bankers Algorithm for DeadLock
Avoidance.
6 Develop a C program to simulate the following contiguous 38-44
memory allocation Techniques: a) Worst fit b) Best fit c)
First fit.
7 Develop a C program to simulate page 45-49
replacement algorithms:
a) FIFO b) LRU
Simulate following File Organization Techniques 50-54
8
a) Single level directory b) Two level directory
19 Develop a C program to simulate the Linked file allocation strategies. 55-56

10 Develop a C program to simulate SCAN disk scheduling algorithm. 57-59


Opearting Systems Lab Manual(BCS303) 2023-24

INTRODUCTION TO OPERATING SYSTEMS


To the study the functions of an operating system.

1.1 OVERVIEW
An Operating System (OS)(as shown in Fig 1) is an interface between a computer user and computer hardware.
An operating system is a software which performs all the basic tasks like file management, memory
management, process management, handling input and output, and controlling peripheral devices such as disk
drives and printers.
Some popular Operating Systems include Linux Operating System, Windows Operating System, VMS, OS/400,
AIX, z/OS, etc. Following are some of important functions of an operating System:

• Memory Management

• Processor Management

• Device Management

• File Management

• Security

• Control over system performance

• Job accounting

• Error detecting aids

• Coordination between other software and end users.

Figure 1. Operating System

Information Science & Engineering,AIT Bangalore 9


Opearting Systems Lab Manual(BCS303) 2023-24

1.2 LINUX OPERATING SYSTEM

Linux is a free and open source operating system and it is a clone version of UNIX operating system. It is open
source as its source code is freely available. It is free to use. Linux was designed considering UNIX
compatibility. Its functionality list is quite similar to that of UNIX.

1.2.1 LINUX ARCHITECTURE

Figure 2. Linux OS Architecture


The architecture of a linux system consists of the following layers −

Hardware layer Hardware consists of all peripheral devices (RAM/ HDD/ CPU etc).

Kernel It is the core component of Operating System, interacts directly with hardware, provides low level
services to upper layer components.

Shell An interface to kernel, hiding complexity of kernel's functions from users.

The shell takes commands from the user and executes kernel's functions.

Utilities Utility programs that provide the user most of the functionalities of an operating systems.

Information Science & Engineering,AIT Bangalore 10


Opearting Systems Lab Manual(BCS303) 2023-24

1.2.2 COMPONENTS OF A LINUX OPERATING SYSTEM


Linux operating system has primarily three components:

Kernel

Kernel is the core part of linux. It is responsible for all major activities of this operating system. It consists of
various modules and it interacts directly with the underlying hardware. Kernel provides the required abstraction to
hide low level hardware details to system or application programs.

System Library

System libraries are special functions or programs using which application programs or system utilities accesses
Kernel's features. These libraries implement most of the functionalities of the operating system and do not requires
kernel module's code access rights.
System Utility

System Utility programs are responsible to do specialized, individual level tasks.

Figure 3. Linux Operating System

1.2.3 KERNEL MODE VS USER MODE

Kernel component code executes in a special privileged mode called kernel mode with full access to all resources
of the computer. This code represents a single process, executes in single address space and do not require any
context switch and hence is very efficient and fast. Kernel runs each processes and provides system services to
processes, provides protected access to hardware to processes.
Support code which is not required to run in kernel mode is in System Library. User programs and other system
programs works in User Mode which has no access to system hardware and kernel code. User programs/ utilities
use System libraries to access Kernel functions to get system's low level tasks.

Information Science & Engineering,AIT Bangalore 11


Opearting Systems Lab Manual(BCS303) 2023-24

1.2.4 BASIC FEATURES

Following are some of the important features of linux operating system


• Portable Portability means software can work on different types of hardware in same way. Linux kernel
and application programs supports their installation on any kind of hardware platform.

• Open Source Linux source code is freely available and it is community based development project.
Multiple teams work in collaboration to enhance the capability of Linux operating system and it is
continuously evolving.

• Multi User Linux is a multiuser system means multiple users can access system resources like memory/
ram/ application programs at same time.

• Multiprogramming Linux is a multiprogramming system means multiple applications can run at same
time.

• Hierarchical File System Linux provides a standard file structure in which system files/ user files are
arranged.

• Shell Linux provides a special interpreter program which can be used to execute commands of the operating
system. It can be used to do various types of operations, call application programs. etc.

• Security Linux provides user security using authentication features like password protection/ controlled
access to specific files/ encryption of data.

1.3 COMPARISONS BETWEEN LINUX OS WITH DIFFERENT OS

1.3.1 LINUX VS WINDOWS

Linux OS Linux could be a free and open supply OS supported operating system standards. It provides
programming interface still as programme compatible with operating system primarily based systems and provides
giant selection applications. A UNIX operating system additionally contains several severally developed parts,
leading to UNIX operating system that is totally compatible and free from proprietary.

Windows OS Windows may be a commissioned OS within which ASCII text file is inaccessible. it’s designed
for the people with the angle of getting no programming information and for business and alternative industrial
users. it‟s terribly straightforward and simple to use.

The distinction between Linux and Windows package is that Linux is completely freed from price whereas
windows is marketable package and is expensive. Associate operating system could be a program meant to regulate
the pc or computer hardware.
Linux is an open supply package wherever users will access the ASCII text file and might improve the code
victimisation the system. On the opposite hand, in windows, users can’t access ASCII text file, and it’s an
authorized OS.

Information Science & Engineering,AIT Bangalore 12


Opearting Systems Lab Manual(BCS303) 2023-24

Let’s sees that the difference between Linux and windows:

1.3.2 LINUX VS MAC

Linux

Linux is a group of open source Unix-like operating systems which was developed by Linus
Torvalds. It is a packaged of Linux distribution. Some of the mostly used Linux distribution are Debian, Fedora
and Ubuntu. It was basically written in C language and assembly language. Kernel used in Linux is Monolithic
kernel. The target systems of Linux distributions are cloud computing, embedded systems, mobile devices,
personal computers, servers, mainframe computers and supercomputers. The first version of Linux was launched
in 1991.

MAC

Mac OS is a series of proprietary graphical operating systems which is provided by Apple


Incorporation. It was earlier known as Mac OS X and later OS X. It is specifically designed for
Apple mac computers. It is based on Unix operating system. It was developed using C, C++, Objective-C, assembly
language and Swift. It is the second most used operating system in personal computers after Windows. The first
version of macOS was launched by Apple in 2001.

Information Science & Engineering,AIT Bangalore 13


Opearting Systems Lab Manual(BCS303) 2023-24

Let’s sees that the difference between Linux and mac:

1.3.3 LINUX VS UNIX

Linux

Linux is an open source multi-tasking, multi-user operating system. It was initially developed by Linus Torvalds
in 1991. Linux OS is widely used in desktops, mobiles, mainframes etc.

Unix

Unix is multi-tasking, multi-user operating system but is not free to use and is not open source. It was developed
in 1969 by Ken Thompson team at AT&T Bell Labs. It is widely used on servers, workstations etc. Following are
the important differences between Linux and Unix.
Let’s sees that the difference between Linux and windows:

Information Science & Engineering,AIT Bangalore 14


Opearting Systems Lab Manual(BCS303) 2023-24

1.4 SCHEDULING OF JOBS IN OPERATING SYSTEM

Job scheduling is the process of allocating system resources to many different tasks by an operating system (OS).
The system handles prioritized job queues that are awaiting CPU time and it should determine which job to be
taken from which queue and the amount of time to be allocated for the job.
This type of scheduling makes sure that all jobs are carried out fairly and on time. Most OSs like Unix,
Windows, etc., include standard job-scheduling abilities. A number of programs including database management
systems (DBMS), backup, enterprise resource planning (ERP) and business process management (BPM) feature
specific job scheduling capabilities as well.
1.5 PROCESS MANAGEMENT

Process management involves various tasks like creation, scheduling, termination of processes, and a dead lock.
Process is a program that is under execution, which is an important part of modern-day operating systems. The
OS must allocate resources that enable processes to share and exchange information.
It also protects the resources of each process from other methods and allows synchronization among processes. It
is the job of OS to manage all the running processes of the system. It handles operations by performing tasks like
process scheduling and such as resource allocation.
1.6 PROCESS ARCHITECTURE

Stack The stack stores temporary data like function parameters, returns addresses, and localvariables.

Heap It allocates memory, which may be processed during its run time.

Data It contains the variable

Text It includes the current activity, which is represented by the value of the Program Counter.

Information Science & Engineering,AIT Bangalore 15


Opearting Systems Lab Manual(BCS303) 2023-24

1.7 MEMORY MANAGEMENT IN OPERATING SYSTEMS

Memory management is the functionality of an operating system which handles or manages primary memory and
moves processes back and forth between main memory and disk during execution. Memory management keeps
track of each and every memory location, regardless of either it is allocated to some process or it is free. It checks
how much memory is to be allocated to processes. It decides which process will get memory at what time. It
tracks whenever some memory gets freed or unallocated and correspondingly it updates the status.
The operating system takes care of mapping the logical addresses to physical addresses at the time of memory
allocation to the program. There are three types of addresses used in a program before and after memory is
allocated –

Symbolic addresses
The addresses used in a source code. The variable names, constants, and instruction labels are the basic elements
of the symbolic address space.

Relative addresses

At the time of compilation, a compiler converts symbolic addresses into relative addresses.

Physical addresses

The loader generates these addresses at the time when a program is loaded into main memory.

1.8 SYSTEM CALLS IN OPERATING SYSTEMS

System call is a mechanism that provides the interface between a process and the operating system. It is a
programmatic method in which a computer program requests a service from the kernel of the OS. System call
offers the services of the operating system to the user programs via API (Application Programming Interface).
System calls are the only entry points for the kernel system. For example, if we need to write a program code to
read data from one file, copy that data into another file.
The first information that the program requires is the name of the two files, the input and output files. In an
interactive system, this type of program execution requires some system calls by OS.
• First call is to write a prompting message on the screen.

• Second, to read from the keyboard, the characters which define the two files.

1.9 DAY TO DAY USAGE OF OPERATING SYSTEMS

The operating system is used everywhere nowadays especially such as banks, schools, colleges, universities,
govt. organizations, IT companies, mobile, etc, …
No device can operate without an operating system because it controls all the user’s commands. Linux /unix
operating systems is used in bank because it’s very secure operating systems.
Symbian OS, windows mobile, IOS and Android OS are used in mobile phones operating systems as these
operating systems are a lightweight operating systems.

Information Science & Engineering,AIT Bangalore 16


Opearting Systems Lab Manual(BCS303) 2023-24

LABORATORY PROGRAMS

1) Develop a c program to implement the Process system calls (fork (), exec(), wait(), create
process, terminate process) .

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
pid_t child_pid;
int status;

// Create a child process


child_pid = fork();

if (child_pid < 0)
{
// Fork failed
perror("Fork failed");
exit(1);
} else if (child_pid == 0)
{
// Child process
printf("Child process (PID: %d) is running.\n", getpid());

// Replace the child process with a new program


execlp("/bin/ls", "ls", "-l", NULL);

// If exec fails, the code below will be executed


perror("Exec failed");
exit(1);
} else
{
// Parent process
printf("Parent process (PID: %d) created a child (PID: %d).\n", getpid(), child_pid);

// Wait for the child process to finish


wait(&status);

if (WIFEXITED(status)) {
printf("Child process (PID: %d) exited with status %d.\n", child_pid, WEXITSTATUS(status));
}
else {
printf("Child process (PID: %d) did not exit normally.\n", child_pid);
}
Information Science & Engineering,AIT Bangalore 17
Opearting Systems Lab Manual(BCS303) 2023-24
}

return 0;
}

OUTPUT:

Information Science & Engineering,AIT Bangalore 18


Opearting Systems Lab Manual(BCS303) 2023-24

// C program to demonstrate working of wait()


#include<stdio.h>
#include<sys/wait.h>
#include<unistd.h>
int main()
{
if (fork()== 0){
printf("HC: hello from child\n");
printf("Child is sleeping\n");
for(int i=0;i<10;i++){
printf("i= %d\n",i);
sleep(1);
}
//sleep(2);
}
else
{
printf("HP: hello from parent\n");
wait(NULL);
printf("CT: child has terminated\n");
printf("PT: Parent terminated ");
}
printf("Bye\n");
return 0;
}

OUTPUT :

Information Science & Engineering,AIT Bangalore 19


Opearting Systems Lab Manual(BCS303) 2023-24

2) Simulate the following CPU scheduling algorithms to find turnaround time and waiting
time a) FCFS b) SJF c) Round Robin d) Priority.

A)FCFS (First Come First Serve)


#include<stdio.h>
int main()
{
int bt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,temp;
float avg_wt,avg_tat;
printf("Enter number of process:");
scanf("%d",&n);
printf("\nEnter Burst Time:\n");
for(i=0;i<n;i++)
{
printf("p % d:",i+1);
scanf("%d",&bt[i]);
p[i]=i+1; //contains process number
}
wt[0]=0; //waiting time for first process will be zero
//calculate waiting time
for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];
total+=wt[i];
}
avg_wt=(float)total/n; //average waiting time
total=0;
printf("\nProcess\t Burst Time \tWaiting Time\tTurnaround Time");
for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i]; //calculate turnaround time
total+=tat[i];
printf("\np%d\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}
avg_tat=(float)total/n; //average turnaround time
printf("\n\nAverage Waiting Time=%f",avg_wt);
printf("\nAverage Turnaround Time=%f\n",avg_tat);
}

Information Science & Engineering,AIT Bangalore 20


Opearting Systems Lab Manual(BCS303) 2023-24

OUTPUT:

Information Science & Engineering,AIT Bangalore 21


Opearting Systems Lab Manual(BCS303) 2023-24

B) SJF (Shortest Job First)


#include<stdio.h>
int main()
{
int bt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,temp;
float avg_wt,avg_tat;
printf("Enter number of process:");
scanf("%d",&n);
printf("\nEnter Burst Time:\n");
for(i=0;i<n;i++)
{
printf("p%d:",i+1);
scanf("%d",&bt[i]);
p[i]=i+1; //contains process number
}
//sorting burst time in ascending order using selection sort
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(bt[j]<bt[pos])
pos=j;
}
temp=bt[i];
bt[i]=bt[pos];
bt[pos]=temp;
temp=p[i];
p[i]=p[pos];
p[pos]=temp;
}
wt[0]=0; //waiting time for first process will be zero
//calculate waiting time
for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];
total+=wt[i];
}
avg_wt=(float)total/n; //average waiting time
total=0;
printf("\nProcess\t Burst Time \tWaiting Time\tTurnaround Time");
for(i=0;i<n;i++)
{

Information Science & Engineering,AIT Bangalore 22


Opearting Systems Lab Manual(BCS303) 2023-24

tat[i]=bt[i]+wt[i]; //calculate turnaround time


total+=tat[i];
printf("\np%d\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}
avg_tat=(float)total/n; //average turnaround time
printf("\n\nAverage Waiting Time=%f",avg_wt);
printf("\nAverage Turnaround Time=%f\n",avg_tat);
}

OUTPUT :

Information Science & Engineering,AIT Bangalore 23


Opearting Systems Lab Manual(BCS303) 2023-24

C) Round Robin

#include<stdio.h>
int main()
{
int i,j,n,bu[10],wa[10],tat[10],t,ct[10],max;
float awt=0,att=0,temp=0;
printf("Enter the no of processes -- ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for process %d -- ", i+1);
scanf("%d",&bu[i]);
ct[i]=bu[i];
}
printf("\nEnter the size of time slice -- ");
scanf("%d",&t);
max=bu[0];
for(i=1;i<n;i++)
if(max<bu[i])
max=bu[i];
for(j=0;j<(max/t)+1;j++)
for(i=0;i<n;i++)
if(bu[i]!=0)
if(bu[i]<=t) {
tat[i]=temp+bu[i];
temp=temp+bu[i];
bu[i]=0;
}
else {
bu[i]=bu[i]-t;
temp=temp+t;
}
for(i=0;i<n;i++){
wa[i]=tat[i]-ct[i];
att+=tat[i];
awt+=wa[i];}
printf("\nThe Average Turnaround time is -- %f",att/n);
printf("\nThe Average Waiting time is -- %f ",awt/n);

printf("\n\tPROCESS\t BURST TIME \t WAITING TIME\tTURNAROUND TIME\n");


for(i=0;i<n;i++)
printf("\t%d \t %d \t\t %d \t\t %d \n",i+1,ct[i],wa[i],tat[i]);
}
Information Science & Engineering,AIT Bangalore 24
Opearting Systems Lab Manual(BCS303) 2023-24

OUTPUT :

Information Science & Engineering,AIT Bangalore 25


Opearting Systems Lab Manual(BCS303) 2023-24

D)Priority
#include<stdio.h>
int main()
{
int bt[20],p[20],wt[20],tat[20],pri[20],i,j,k,n,total=0,pos,temp;
float avg_wt,avg_tat;
printf("Enter number of process:");
scanf("%d",&n);
printf("\nEnter Burst Time:\n");
for(i=0;i<n;i++)
{
printf("p%d:",i+1);
scanf("%d",&bt[i]);
p[i]=i+1; //contains process number
}
printf(" enter priority of the process ");
for(i=0;i<n;i++)
{
p[i] = i;
//printf("Priority of Process");
printf("p%d ",i+1);
scanf("%d",&pri[i]);
}
for(i=0;i<n;i++)
for(k=i+1;k<n;k++)
if(pri[i] > pri[k])
{
temp=p[i];
p[i]=p[k];
p[k]=temp;
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;
temp=pri[i];
pri[i]=pri[k];
pri[k]=temp;
}
wt[0]=0; //waiting time for first process will be zero
//calculate waiting time
for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)

Information Science & Engineering,AIT Bangalore 26


Opearting Systems Lab Manual(BCS303) 2023-24

wt[i]+=bt[j];
total+=wt[i];
}
avg_wt=(float)total/n; //average waiting time
total=0;
printf("\nProcess\t Burst Time \tPriority \tWaiting Time\tTurnaround Time");
for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i]; //calculate turnaround time
total+=tat[i];
printf("\np%d\t\t %d\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],pri[i],wt[i],tat[i]);
}
avg_tat=(float)total/n; //average turnaround time
printf("\n\nAverage Waiting Time=%f",avg_wt);
printf("\nAverage Turnaround Time=%f\n",avg_tat);
}

OUTPUT:

Information Science & Engineering,AIT Bangalore 27


Opearting Systems Lab Manual(BCS303) 2023-24

3) Develop a C program to simulate producer-consumer problem using semaphores.


#include <stdio.h>
#include <stdlib.h>

// Initialize a mutex to 1
int mutex = 1;

// Number of full slots as 0


int full = 0;

// Number of empty slots as size


// of buffer
int empty = 10, x = 0;

// Function to produce an item and


// add it to the buffer
void producer()
{
// Decrease mutex value by 1
--mutex;

// Increase the number of full


// slots by 1
++full;

// Decrease the number of empty


// slots by 1
--empty;

// Item produced
x++;
printf("\nProducer produces"
"item %d",
x);

// Increase mutex value by 1


++mutex;
}

// Function to consume an item and


// remove it from buffer
void consumer()
{
// Decrease mutex value by 1
--mutex;
Information Science & Engineering,AIT Bangalore 28
Opearting Systems Lab Manual(BCS303) 2023-24

// Decrease the number of full


// slots by 1
--full;

// Increase the number of empty


// slots by 1
++empty;
printf("\nConsumer consumes "
"item %d",
x);
x--;

// Increase mutex value by 1


++mutex;
}

// Driver Code
int main()
{
int n, i;
printf("\n1. Press 1 for Producer"
"\n2. Press 2 for Consumer"
"\n3. Press 3 for Exit");

// Using '#pragma omp parallel for'


// can give wrong value due to
// synchronization issues.

// 'critical' specifies that code is


// executed by only one thread at a
// time i.e., only one thread enters
// the critical section at a given time
#pragma omp critical

for (i = 1; i > 0; i++) {

printf("\nEnter your choice:");


scanf("%d", &n);

// Switch Cases
switch (n) {
case 1:

// If mutex is 1 and empty


// is non-zero, then it is
// possible to produce

Information Science & Engineering,AIT Bangalore 29


Opearting Systems Lab Manual(BCS303) 2023-24

if ((mutex == 1)
&& (empty != 0)) {
producer();
}

// Otherwise, print buffer


// is full
else {
printf("Buffer is full!");
}
break;

case 2:

// If mutex is 1 and full


// is non-zero, then it is
// possible to consume
if ((mutex == 1)
&& (full != 0)) {
consumer();
}

// Otherwise, print Buffer


// is empty
else {
printf("Buffer is empty!");
}
break;

// Exit Condition
case 3:
exit(0);
break;
}
}
}

Information Science & Engineering,AIT Bangalore 30


Opearting Systems Lab Manual(BCS303) 2023-24

OUTPUT:

Information Science & Engineering,AIT Bangalore 31


Opearting Systems Lab Manual(BCS303) 2023-24

4) Develop a C program which demonstrates interprocess communication between a reader


process and a writer process. Use mkfifo, open, read, write and close APIs in your
program.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define FIFO_PATH "myfifo"

void writerProcess() {
int fd;
char buffer[] = "Hello, Reader!";

// Create a FIFO (named pipe)


if (mkfifo(FIFO_PATH, 0666) == -1) {
perror("Error creating FIFO");
exit(EXIT_FAILURE);
}

// Open the FIFO for writing


fd = open(FIFO_PATH, O_WRONLY);
if (fd == -1) {
perror("Error opening FIFO for writing");
exit(EXIT_FAILURE);
}

// Write data to the FIFO


write(fd, buffer, sizeof(buffer));

// Close the FIFO


close(fd);

// Remove the FIFO


unlink(FIFO_PATH);
}

void readerProcess() {
int fd;
char buffer[50];

// Open the FIFO for reading


fd = open(FIFO_PATH, O_RDONLY);

Information Science & Engineering,AIT Bangalore 32


Opearting Systems Lab Manual(BCS303) 2023-24

if (fd == -1) {
perror("Error opening FIFO for reading");
exit(EXIT_FAILURE);
}

// Read data from the FIFO


read(fd, buffer, sizeof(buffer));

// Display the read data


printf("Reader Process: Received message - %s\n", buffer);

// Close the FIFO


close(fd);
}

int main() {
pid_t pid;

// Fork a child process


pid = fork();
if (pid < 0) {
perror("Fork failed");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// Child process (writer)
writerProcess();
} else {
// Parent process (reader)
readerProcess();
}

return 0;
}

OUTPUT:

Information Science & Engineering,AIT Bangalore 33


Opearting Systems Lab Manual(BCS303) 2023-24

5) Develop a C program to simulate Bankers Algorithm for DeadLock Avoidance.


#include <stdio.h>

int main()
{

// P0, P1, P2, P3, P4 are the Process names here

int n, m, i, j, k;

n = 5; // Number of processes

m = 3; // Number of resources

int alloc[5][3] = { { 0, 1, 0 }, // P0 // Allocation Matrix

{ 2, 0, 0 }, // P1

{ 3, 0, 2 }, // P2

{ 2, 1, 1 }, // P3

{ 0, 0, 2 } }; // P4

int max[5][3] = { { 7, 5, 3 }, // P0 // MAX Matrix

{ 3, 2, 2 }, // P1

{ 9, 0, 2 }, // P2

{ 2, 2, 2 }, // P3

{ 4, 3, 3 } }; // P4

int avail[3] = { 3, 3, 2 }; // Available Resources

int f[n], ans[n], ind = 0;

for (k = 0; k < n; k++) {

f[k] = 0;

Information Science & Engineering,AIT Bangalore 34


Opearting Systems Lab Manual(BCS303) 2023-24
}

int need[n][m];

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

for (j = 0; j < m; j++)

need[i][j] = max[i][j] - alloc[i][j];

int y = 0;

for (k = 0; k < 5; k++) {

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

if (f[i] == 0) {

int flag = 0;

for (j = 0; j < m; j++) {

if (need[i][j] > avail[j]){

flag = 1;

break;

if (flag == 0) {

ans[ind++] = i;

for (y = 0; y < m; y++)

avail[y] += alloc[i][y];

f[i] = 1;

}
Information Science & Engineering,AIT Bangalore 35
Opearting Systems Lab Manual(BCS303) 2023-24

int flag = 1;

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

if(f[i]==0)

flag=0;

printf("The following system is not safe");

break;

if(flag==1)

printf("Following is the SAFE Sequence\n");

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

printf(" P%d ->", ans[i]);

printf(" P%d", ans[n - 1]);

return (0);

Information Science & Engineering,AIT Bangalore 36


Opearting Systems Lab Manual(BCS303) 2023-24

OUTPUT:

ise@ise-HP-Compaq-8200-Elite-MT-PC:~$ gcc p5.c

ise@ise-HP-Compaq-8200-Elite-MT-PC:~$ ./a.out

Following is the SAFE Sequence

P1 -> P3 -> P4 -> P0 -> P2ise@ise-HP-Compaq-8200-Elite-MT-PC:~$

Information Science & Engineering,AIT Bangalore 37


Opearting Systems Lab Manual(BCS303) 2023-24

6) Develop a C program to simulate the following contiguous memory allocation


Techniques: a) Worst fit b) Best fit c) First fit.

A) Worst fit
#include <stdio.h>
#define MAX_BLOCKS 100
struct MemoryBlock
{
int block_id;
int size;
int allocated;
};

void worstFit(struct MemoryBlock blocks[], int m, int processSize)


{
int worstIdx = -1;
for (int i = 0; i < m; i++)
{
if (blocks[i].allocated == 0 && blocks[i].size >= processSize)
{
if (worstIdx == -1 || blocks[i].size > blocks[worstIdx].size)
{
worstIdx = i;
}
}
}
if (worstIdx != -1) {
blocks[worstIdx].allocated = 1;
printf("Process with size %d allocated to block %d\n", processSize, worstIdx + 1);
}
else
{
printf("Cannot allocate the process with size %d\n", processSize);
}
}
int main() {
int m;
printf("Enter the number of memory blocks: ");
scanf("%d", &m);
struct MemoryBlock blocks[MAX_BLOCKS];
for (int i = 0; i < m; i++)
{
blocks[i].block_id = i + 1;
printf("Enter the size of memory block %d: ", i + 1);
scanf("%d", &blocks[i].size);

Information Science & Engineering,AIT Bangalore 38


Opearting Systems Lab Manual(BCS303) 2023-24

blocks[i].allocated = 0;
}
int n;
printf("Enter the number of processes: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
int processSize;
printf("Enter the size of process %d: ", i + 1);
scanf("%d", &processSize);
worstFit(blocks, m, processSize);
}
return 0;
}

OUTPUT:

Information Science & Engineering,AIT Bangalore 39


Opearting Systems Lab Manual(BCS303) 2023-24

B) Best fit
#include <stdio.h>
// Define the maximum number of memory blocks
#define MAX_BLOCKS 100
// Structure to represent memory blocks
struct MemoryBlock {
int block_id;
int size;
int allocated;
};
// Function to perform best-fit memory allocation
void bestFit(struct MemoryBlock blocks[], int m, int processSize) {
int bestIdx = -1;
for (int i = 0; i < m; i++) {
if (blocks[i].allocated == 0 && blocks[i].size >= processSize) {
if (bestIdx == -1 || blocks[i].size < blocks[bestIdx].size) {
bestIdx = i;
}}
}
if (bestIdx != -1) {
// Allocate the memory block
blocks[bestIdx].allocated = 1;
printf("Process with size %d allocated to block %d\n", processSize, bestIdx + 1);
} else {
printf("Cannot allocate the process with size %d\n", processSize);
}
}
int main() {
int m; // Number of memory blocks
printf("Enter the number of memory blocks: ");
scanf("%d", &m);
struct MemoryBlock blocks[MAX_BLOCKS];
for (int i = 0; i < m; i++) {
blocks[i].block_id = i + 1;
printf("Enter the size of memory block %d: ", i + 1);
scanf("%d", &blocks[i].size);
blocks[i].allocated = 0; // Initialize as unallocated
}
int n; // Number of processes
printf("Enter the number of processes: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
Information Science & Engineering,AIT Bangalore 40
Opearting Systems Lab Manual(BCS303) 2023-24

int processSize;
printf("Enter the size of process %d: ", i + 1);
scanf("%d", &processSize);
bestFit(blocks, m, processSize);
}
return 0;
}

OUTPUT:

Information Science & Engineering,AIT Bangalore 41


Opearting Systems Lab Manual(BCS303) 2023-24

b1. Best fit

#include <stdio.h>
// Number of memory blocks
#define NUM_BLOCKS 5
// Number of processes
#define NUM_PROCESSES 5
// Sizes of memory blocks
int memory_blocks[NUM_BLOCKS] = {100, 500, 200, 300, 600};
// Sizes of processes
int process_sizes[NUM_PROCESSES] = {212, 417, 112, 426, 112};
// Array to keep track of whether a block is allocated or not
int allocated[NUM_BLOCKS] = {0};
// Function to perform Best Fit memory allocation
void bestFit() {
for (int i = 0; i < NUM_PROCESSES; i++) {
int best_fit_index = -1;
for (int j = 0; j < NUM_BLOCKS; j++) {
if (!allocated[j] && memory_blocks[j] >= process_sizes[i]) {
if (best_fit_index == -1 || memory_blocks[j] < memory_blocks[best_fit_index]) {
best_fit_index = j;
}
}
}
if (best_fit_index != -1) {
allocated[best_fit_index] = 1;
printf("Process %d (size %d) is allocated to Block %d (size %d)\n",
i, process_sizes[i], best_fit_index, memory_blocks[best_fit_index]);
} else {
printf("Process %d (size %d) cannot be allocated\n", i, process_sizes[i]);
}
}
}
int main() {
bestFit();
return 0;
}

Information Science & Engineering,AIT Bangalore 42


Opearting Systems Lab Manual(BCS303) 2023-24

OUTPUT:

C. First fit

#include <stdio.h>
// Define the maximum number of memory blocks
#define MAX_BLOCKS 100
// Structure to represent memory blocks
struct MemoryBlock {
int block_id;
int size;
int allocated;
};
// Function to perform first-fit memory allocation
void firstFit(struct MemoryBlock blocks[], int m, int processSize) {
for (int i = 0; i < m; i++) {
if (blocks[i].allocated == 0 && blocks[i].size >= processSize) {
// Allocate the memory block
blocks[i].allocated = 1;
printf("Process with size %d allocated to block %d\n", processSize, i + 1);
return;
}
}
printf("Cannot allocate the process with size %d\n", processSize);
}
int main() {
int m; // Number of memory blocks
printf("Enter the number of memory blocks: ");
scanf("%d", &m);
struct MemoryBlock blocks[MAX_BLOCKS];
for (int i = 0; i < m; i++) {
blocks[i].block_id = i + 1;
Information Science & Engineering,AIT Bangalore 43
Opearting Systems Lab Manual(BCS303) 2023-24
printf("Enter the size of memory block %d: ", i + 1);
scanf("%d", &blocks[i].size);
blocks[i].allocated = 0; // Initialize as unallocated
}
int n; // Number of processes
printf("Enter the number of processes: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
int processSize;
printf("Enter the size of process %d: ", i + 1);
scanf("%d", &processSize);
firstFit(blocks, m, processSize);
}
return 0;
}

OUTPUT:

Information Science & Engineering,AIT Bangalore 44


Opearting Systems Lab Manual(BCS303) 2023-24

7) Develop a C program to simulate page replacement algorithms: a) FIFO b) LRU


A) FIFO

#include <stdio.h>
int main()
{
int incomingStream[] = {4 , 1 , 2 , 4 , 5,4,1,2,3,6};
int pageFaults = 0;
int frames = 3;
int m, n, s, pages;
pages = sizeof(incomingStream)/sizeof(incomingStream[0]);
printf(" Incoming \t Frame 1 \t Frame 2 \t Frame 3 ");
int temp[ frames ];
for(m = 0; m < frames; m++)
{
temp[m] = -1;
}
for(m = 0; m < pages; m++)
{
s = 0;
for(n = 0; n < frames; n++)
{
if(incomingStream[m] == temp[n])
{
s++;
pageFaults--;
}
}
pageFaults++;

if((pageFaults <= frames) && (s == 0))


{
temp[m] = incomingStream[m];
}
else if(s == 0)
{
temp[(pageFaults - 1) % frames] = incomingStream[m];
}
printf("\n");
printf("%d\t\t\t",incomingStream[m]);
for(n = 0; n < frames; n++)
{
if(temp[n] != -1)
printf(" %d\t\t\t", temp[n]);
else
printf(" - \t\t\t");
Information Science & Engineering,AIT Bangalore 45
Opearting Systems Lab Manual(BCS303) 2023-24
}
}
printf("\nTotal Page Faults:\t%d\n", pageFaults);
return 0;
}

OUTPUT:

Information Science & Engineering,AIT Bangalore 46


Opearting Systems Lab Manual(BCS303) 2023-24

B) LRU

#include<stdio.h>
#include<limits.h>
int checkHit(int incomingPage, int queue[], int occupied){

for(int i = 0; i < occupied; i++){


if(incomingPage == queue[i])
return 1;
}

return 0;
}
void printFrame(int queue[], int occupied)
{
for(int i = 0; i < occupied; i++)
printf("%d\t\t\t",queue[i]);
}
int main()
{
// int incomingStream[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1};
// int incomingStream[] = {1, 2, 3, 2, 1, 5, 2, 1, 6, 2, 5, 6, 3, 1, 3, 6, 1, 2, 4, 3};
int incomingStream[] = {1, 2, 3, 2, 1, 5, 2, 1, 6, 2, 5, 6, 3, 1, 3};

int n = sizeof(incomingStream)/sizeof(incomingStream[0]);
int frames = 3;
int queue[n];
int distance[n];
int occupied = 0;
int pagefault = 0;

printf("Page\t Frame1 \t Frame2 \t Frame3\n");

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


{
printf("%d: \t\t",incomingStream[i]);
// what if currently in frame 7
// next item that appears also 7
// didnt write condition for HIT

if(checkHit(incomingStream[i], queue, occupied)){


printFrame(queue, occupied);
}

// filling when frame(s) is/are empty


else if(occupied < frames){
queue[occupied] = incomingStream[i];
pagefault++;
occupied++;

Information Science & Engineering,AIT Bangalore 47


Opearting Systems Lab Manual(BCS303) 2023-24

printFrame(queue, occupied);
}
else{

int max = INT_MIN;


int index;
// get LRU distance for each item in frame
for (int j = 0; j < frames; j++)
{
distance[j] = 0;
// traverse in reverse direction to find
// at what distance frame item occurred last
for(int k = i - 1; k >= 0; k--)
{
++distance[j];
if(queue[j] == incomingStream[k])
break;
}

// find frame item with max distance for LRU


// also notes the index of frame item in queue
// which appears furthest(max distance)
if(distance[j] > max){
max = distance[j];
index = j;
}
}
queue[index] = incomingStream[i];
printFrame(queue, occupied);
pagefault++;
}

printf("\n");
}

printf("Page Fault: %d",pagefault);

return 0;
}

Information Science & Engineering,AIT Bangalore 48


Opearting Systems Lab Manual(BCS303) 2023-24

OUTPUT:

Information Science & Engineering,AIT Bangalore 49


Opearting Systems Lab Manual(BCS303) 2023-24

8 ) Simulate following File Organization Techniques


a) Single level directory b) Two level directory

a) Single level directory

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Maximum number of files in the directory
#define MAX_FILES 100
// Maximum file name length
#define MAX_NAME_LENGTH 256
// File structure to represent files
typedef struct File {
char name[MAX_NAME_LENGTH];
int size;
char content[1024]; // For simplicity, we use a fixed content size
} File;
// Directory structure to hold files
typedef struct Directory {
File files[MAX_FILES];
int num_files;
} Directory;
// Function to create a new file
File createFile(const char* name, int size, const char* content)
{
File newFile;
strncpy(newFile.name, name, MAX_NAME_LENGTH);
newFile.size = size;
strncpy(newFile.content, content, sizeof(newFile.content));
return newFile;
}
// Function to add a file to the directory
void addFileToDirectory(Directory* directory, File file) {
if (directory->num_files < MAX_FILES) {
directory->files[directory->num_files] = file;
directory->num_files++;
} else {
printf("Directory is full. Cannot add more files.\n");
}
}
// Function to display the contents of the directory
void displayDirectoryContents(const Directory* directory) {
printf("Directory Contents:\n");
for (int i = 0; i < directory->num_files; i++) {
printf("File: %s, Size: %d\n", directory->files[i].name, directory->files[i].size);
}
}
Information Science & Engineering,AIT Bangalore 50
Opearting Systems Lab Manual(BCS303) 2023-24

int main() {
Directory directory;
directory.num_files = 0;

// Create and add files to the directory

File file1 = createFile("File1.txt", 100, "This is the content of File1.");


addFileToDirectory(&directory, file1);
File file2 = createFile("File2.txt", 200, "Content of File2 goes here.");
addFileToDirectory(&directory, file2);
// Display the directory contents
displayDirectoryContents(&directory);
return 0;
}

OUTPUT :

Information Science & Engineering,AIT Bangalore 51


Opearting Systems Lab Manual(BCS303) 2023-24

b) Two level directory


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_DIRS 100
#define MAX_FILES 100
struct FileEntry {
char name[50];
char content[1000];
};
struct Directory {
char name[50];
struct FileEntry files[MAX_FILES];
int num_files;
};
int num_dirs = 0;
struct Directory directories[MAX_DIRS];
void createDirectory(char parent_name[], char dir_name[]) {
if (num_dirs >= MAX_DIRS) {
printf("Error: Maximum directories reached.\n");
return;
}
for (int i = 0; i < num_dirs; i++) {
if (strcmp(directories[i].name, parent_name) == 0) {
if (directories[i].num_files >= MAX_FILES) {
printf("Error: Maximum files reached in %s.\n", parent_name);
return;
}
strcpy(directories[num_dirs].name, dir_name);

directories[i].files[directories[i].num_files].content[0] = '\0';
directories[i].num_files++;
num_dirs++;
printf("Directory %s created in %s.\n", dir_name, parent_name);
return;
}
}
printf("Error: Parent directory not found.\n");
}
void createFile(char dir_name[], char file_name[]) {
for (int i = 0; i < num_dirs; i++) {
if (strcmp(directories[i].name, dir_name) == 0) {
if (directories[i].num_files >= MAX_FILES) {

Information Science & Engineering,AIT Bangalore 52


Opearting Systems Lab Manual(BCS303) 2023-24

printf("Error: Maximum files reached in %s.\n", dir_name);


return;
}
strcpy(directories[i].files[directories[i].num_files].name, file_name);
directories[i].files[directories[i].num_files].content[0] = '\0';
directories[i].num_files++;
printf("File %s created in %s.\n", file_name, dir_name);
return;
}
}
printf("Error: Directory not found.\n");
}
void listFiles(char dir_name[]) {
for (int i = 0; i < num_dirs; i++) {
if (strcmp(directories[i].name, dir_name) == 0) {
printf("Files in directory %s:\n", dir_name);
for (int j = 0; j < directories[i].num_files; j++) {
printf("%s\n", directories[i].files[j].name);
}
return;
}
}
printf("Error: Directory not found.\n");
}
int main() {
strcpy(directories[0].name, "root");
directories[0].num_files = 0;
num_dirs++;
char parent[50], dir[50], file[50];
createDirectory("root", "docs");
createDirectory("root", "images");
createFile("docs", "document1.txt");
createFile("docs", "document2.txt");
createFile("images", "image1.jpg");
listFiles("docs");
listFiles("images");
return 0;
}

Information Science & Engineering,AIT Bangalore 53


Opearting Systems Lab Manual(BCS303) 2023-24

OUTPUT :

Information Science & Engineering,AIT Bangalore 54


Opearting Systems Lab Manual(BCS303) 2023-24

9) Develop a C program to simulate the Linked file allocation strategies.


#include <stdio.h>
#include <stdlib.h>
int main(){
int f[50], p, i, st, len, j, c, k, a;
for (i = 0; i < 50; i++)
f[i] = 0;
printf("Enter how many blocks already allocated: ");
scanf("%d", &p);
printf("Enter blocks already allocated: ");
for (i = 0; i < p; i++) {
scanf("%d", &a);
f[a] = 1;
}
x:
printf("Enter index starting block and length: ");
scanf("%d%d", &st, &len);
k = len;
if (f[st] == 0)
{
for (j = st; j < (st + k); j++){
if (f[j] == 0){
f[j] = 1;
printf("%d---->", j);
}
else{
//printf("%d Block is already allocated \n", j);
k++;
}
}
}
else
printf("%d starting block is already allocated \n", st);
printf("Do you want to enter more file(Yes - 1/No - 0)");
scanf("%d", &c);
if (c == 1)
goto x;
else
exit(0);
return 0;
}

Information Science & Engineering,AIT Bangalore 55


Opearting Systems Lab Manual(BCS303) 2023-24

OUTPUT :

Information Science & Engineering,AIT Bangalore 56


Opearting Systems Lab Manual(BCS303) 2023-24

10) Develop a C program to simulate SCAN disk scheduling algorithm.

#include<stdio.h>
#include<stdlib.h>
int main()
{
int queue[20],n,head,i,j,k,seek=0,max,diff,temp,queue1[20],queue2[20],
temp1=0,temp2=0;
float avg;
printf("Enter the max range of disk\n");
scanf("%d",&max);
printf("Enter the initial head position\n");
scanf("%d",&head);
printf("Enter the size of queue request\n");
scanf("%d",&n);
printf("Enter the queue of disk positions to be read\n");
int pos[] = {90,120,35,122,38,128,65,68};
for(i=1;i<=n;i++)
{
//scanf("%d",&temp);
temp = pos[i-1];
if(temp>=head)
{
queue1[temp1]=temp;
temp1++;
}
else
{
queue2[temp2]=temp;
temp2++;
}
}
for(i=0;i<temp1-1;i++)
{
for(j=i+1;j<temp1;j++)
{
if(queue1[i]>queue1[j])
{
temp=queue1[i];
queue1[i]=queue1[j];
queue1[j]=temp;
}
}
}
for(i=0;i<temp2-1;i++)
{

Information Science & Engineering,AIT Bangalore 57


Opearting Systems Lab Manual(BCS303) 2023-24

for(j=i+1;j<temp2;j++)
{
if(queue2[i]<queue2[j])
{
temp=queue2[i];
queue2[i]=queue2[j];
queue2[j]=temp;
}
}
}
for(i=1,j=0;j<temp1;i++,j++)
queue[i]=queue1[j];

//queue[i]=max;
//queue[i+1]=0;
for(i=temp1+1,j=0;j<temp2;i++,j++)
queue[i]=queue2[j];
queue[0]=head;
for(j=0;j<=n-1;j++)
{
diff=abs(queue[j+1]-queue[j]);
seek+=diff;
printf("Disk head moves from %d to %d with seek %d\n",queue[j],queue[j+1],diff);
}
printf("Total seek time is %d\n",seek);
avg=seek/(float)n;
printf("Average seek time is %f\n",avg);
return 0;
}

Information Science & Engineering,AIT Bangalore 58


Opearting Systems Lab Manual(BCS303) 2023-24

OUTPUT:

Information Science & Engineering,AIT Bangalore 59

You might also like