OS Lab Manual
OS Lab Manual
1
Preamble
This manual is designed to equip you with essential skills in using shell commands and scripting
within an operating system environment. Through practical exercises in this manual, you'll learn
how to navigate, automate tasks, and create scripts efficiently. Operating system concepts are
vital for solving real-world challenges. This lab manual will guide you in understanding and
applying principles like process management, memory allocation, and file systems.
By course end, you'll be proficient in shell commands, scripting, and applying operating systems
concepts to tackle real-world issues effectively. Let's dive into this journey together, enhancing
your skills for a successful computing career!
2
Course Objectives:
The course aims to provide exposure to problem-solving through programming. It aims to train
the student to the basic concepts of the C-programming language. This course involves a lab
component which is designed to give the student hands-on experience with the concepts that
develop problem solving and coding skills.
Course Outcome:
Delivery
Domain/level
CO methods
CO Statement of learning Assessment tools
No. and
taxonomy
activities
Lecture,
Demonstrate basic shell Psychomotor/ Class Quiz/Mid-term
1
commands and scripts L2, Affective / Participation exam/Assignments
L2
Lecture, Project, Mid-term
Apply operating systems Psychomotor/ Discussion, exam, Final exam.
2 concepts for solving L3, Affective / Group Work
real-world problems L3
Online Resources:
Lab Instructions
● All students must arrive on time for the class.
● Just after entering and before class started, all students were required to submit their lab
reports (if any).
● All computers must be handled with care.
● Use only the software needed for the course.
● No haste should be done during the class period.
● After a class period, all computers must be shut down.
● Perfect discipline should be maintained and useless talking should be avoided while
performing LAB.
● Food and Drinks are not allowed in the LAB.
● LAB will be used for academic purposes only.
3
OS Lab Manual Contents
Course Objectives 3
Course Outcome 3
Text and Reference Material 3
Lab Instruction 3
Lab Task 1 5
Lab Task 2 10
Lab Task 3 15
Lab Task4 18
Lab Task 5 21
Lab Task 6 23
Lab Task 7 26
Lab Task 8 31
Lab Task 9 34
Lab Task 10 37
Lab Task 11 42
4
Lab Task 01: Introduction to Unix
Part A
A. Overview:
This is the introductory class. An overview of the UNIX operating system, Linux, and required tools are
discussed. Here, expectations from the students, course outcomes, overall lab assessment criteria, etc. are
also covered. Students are informed about the project that they must turn in at the end of the semester as
well.
B. Learning Outcome:
After this lecture, the students will be able to:
a. Learn about the Unix operating system, Linux
b. Install UbuntuWeek 6
E. Background:
UNIX:
It is a multi-user operating system. It is a stable, multi-user, multi-tasking system for servers, desktops,
and laptops. Ken Thomson and Dennis Ritchie developed it from MULTICS (Multiplexed Information
and Computing Service) OS at AT & T Bell Industries, USA in 1969. It was created in an effort to
provide a multiuser, multitasking system for use by programmers By1980, UNIX had been completely
rewritten using C language.
The UNIX operating system is made up of three parts:
● Kernel
● Shell and
● Programs.
LINUX:
Linux is one of the most popular versions of the UNIX operating System. It was created by Linus
Torvalds. All UNIX commands work in Linux. Linux is an open-source software. The main feature of
Linux is coexisting with other OS such as Windows and UNIX.
UNIX KERNEL:
The Linux kernel is its central component. It oversees all of this operating system's important functions. It
comprises different modules and directly communicates with the underlying hardware. The kernel offers
the necessary abstraction to shield the low-level hardware specifications from the user.
5
SHELL:
Shell is the command interpreter in the UNIX OS. It accepts commands from the user and analyses and
interprets them. Most accounts on our clusters have the bash shell by default.
Part B
A. Objective
An overview of the basic UNIX commands.
B. Learning Outcome:
After this lecture, the students will be able to:
a. Learn about Unix shell commands
E. Activity List
Basic UNIX commands are shown below. Students need to write commands and check the output.
6
b) cal: used to display the calendar
Syntax: $cal 2 2009
d)ls: used to list the files. Your files are kept in a directory.
Syntax: $lsls–s
All files (include files with prefix)
ls–l Lodetai (provide file statistics)
ls–t Order by creation time
ls– u Sort by access time (or show when last accessed together with –l)
ls–s Order by size
ls–r Reverse order
ls–f Mark directories with /, executable with* , symbolic links with @, local sockets with =,
named pipes(FIFOs)with
ls–s Show file size
ls– h“ Human Readable”, show file size in Kilo Bytes & Mega Bytes (h can be used
together with –l or)
ls[a-m]*List all the files whose name begin with alphabets From „a‟ to „m‟
ls[a]*List all the files whose name begins with „a‟ or „A‟
Eg:$ls>my list Output of „ls‟ command is stored to a disk file named „my list‟
g)who & whoami: it displays data about all users who have logged into the system currently. The next
command displays the current user only.
Syntax: $who $whoami
h)uptime: tells you how long the computer has been running since its last reboot or power-off.
Syntax: $uptime
i)uname: it displays the system information such as hardware platform, system name, and processor, OS
type.
Syntax:$uname–a
Syntax :$ hostname
7
FILE MANIPULATION COMMANDS
b)grep–used to search a particular word or pattern related to that word from the file.
Syntax:$grep search word filename
Eg:$grep anu student
8
Syntax:$tail filename
Eg:$tail student
To display the bottom two lines;
Syntax:$ tail -2 student
Examples:
$chmodu-wx student
Removes write and execute permission for users
$ch modu+rw,g+rwstudent
Assigns read and write permission for users and groups
$chmodg=rwx student
Assigns absolute permission for groups of all read, write and execute permissions
k)wc–it counts the number of lines, words, characters in a specified file(s) with the options as –l,-w,-c
Category Operation Permission
9
Lab Task 02: Introduction to System Call
Part A
A. Overview:
● To understand about Linux system calls and their use in processes.
● To write C Programs using the following system calls of the UNIX operating system: fork, exec,
getpid, exit, wait, close, stat, opendir, readdir.
B. Learning Outcome:
After this lecture, the students will be able to learn about the Unix System Calls: fork, exec, getpid, exit, wait, close,
stat, opendir, readdir
BACKGROUND:
What are system calls?
System calls provide the means for a user program to ask the operating system to perform tasks reserved for
the operating system on the user program’s behalf. A system call is invoked in a variety of ways, depending
on the functionality provided by the underlying processor. In all forms, it is the method used by a process to
request action by the operating system.
Windows UNIX
10
Process Control System Calls of UNIX System:
III. exit() ● Process terminates its execution by calling the exit() system call
● It returns exit status, which is retrieved by the parent process using wait()
command
● EXIT_SUCCESS // integer value = 0
● EXIT_FAILURE // integer value = 1
● OS reclaims resources allocated by the terminated process (dead process)
Typically
● performs clean-up operations within the process space before returning
control back
● to the OS
● Terminates the current process without any extra program clean-up
● Usually used by the child process to prevent from erroneous release of
resources
● belonging to the parent process
IV. sleep() ● Takes a time value as a parameter (in seconds on Unix-like OS and in
milliseconds on Windows OS)
sleep(2) // sleep for 2 seconds in Unix
Sleep(2*1000) // sleep for 2 seconds in Window
11
VI. getppid() ● returns the PID of the parent of the current process
Activity List:
➔ All programs are shown in the Green boxes.
➔ All the programs should be written in C language.
➔ In the blue box write the appropriate output for each program.
12
Process Tree:
In Lab Exercise:
1. Create a program that creates a child process. The child process prints “I am a child
process” 100 times in a loop. Whereas the parent process prints “I am a parent process”
100 times in a loop.
13
2. Create a program named stat that takes an integer array as an input(delimited by some
character such as $). The program then creates 3 child processes each of which does
exactly one task from the following.
a) Adds them and print the result on the screen. (done by child 1)
b) Shows the average on the screen. (done by child 2)
c) Print the maximum number on the screen. (done by child 3)
14
Lab Task 03: CPU scheduling Algorithm
A. Overview:
Write a C program to simulate the following non-preemptive CPU scheduling algorithms to find the
turnaround time and waiting time for the above problem.
a) FCFS
b) SJF
B. Learning Outcome:
After this lecture, the students will be able to learn about the fundamental concepts of CPU scheduling. Also,
they will be able to learn about different algorithms.
Activity List:
● The steps for each algorithm will be discussed in class.
● Students can use any programming language for implementation.
● Sample Inputs are shown in the Green boxes.
● In the blue box, students should write the appropriate output for each Algorithm.
AIM: To write a c program to simulate the CPU scheduling algorithm First Come First Serve
(FCFS).
DESCRIPTION:
To calculate the average waiting time using the FCFS algorithm first the waiting time of the first process is
kept at zero and the waiting time of the second process is the burst time of the first process and the waiting
time of the third process is the sum of the burst times of the first and the second process and so on. After
calculating all the waiting times the average waiting time is calculated as the average of all the waiting
times. FCFS mainly says first come first serve the algorithm which came first will be served first.
ALGORITHM:
15
Step 5: for each process in the Ready Q calculate
a).Waiting time (n) = waiting time (n-1) + Burst time (n-1)
b). Turnaround time (n)= waiting time(n)+Burst time(n)
Step 6: Calculate
a) Average waiting time = Total waiting Time / Number of processes
b) Average Turnaround time = Total Turnaround Time / Number of processes
Step 7: Stop the process
16
Shortest Job First (SJF):
AIM: To write a program to stimulate the CPU scheduling algorithm Shortest job first (Non-Preemption)
DESCRIPTION:
To calculate the average waiting time in the shortest job first algorithm the sorting of the process based on
their burst time in ascending order then calculate the waiting time of each process as the sum of the bursting
times of all the processes previous or before that process.
ALGORITHM:
Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Queue, assign the process id and accept the CPU burst time
Step 4: Start the Ready Queue according to the shortest Burst time by sorting according to lowest to highest burst time.
Step 5: Set the waiting time of the first process as ‘0’ and its turnaround time as its burst time.
Step 6: Sort the processes names based on their Burt time
Step 7: For each process in the ready queue, calculate
a) Waiting time (n) = waiting time (n-1) + Burst time (n-1)
b) Turnaround time (n) = waiting time(n)+Burst time(n)
Step 8: Calculate
a) Average waiting time = Total waiting Time / Number of processes
b) Average Turnaround time = Total Turnaround Time /number of processes
Step 9: Stop the process
17
Lab Task 04: CPU scheduling Algorithm
A. Overview:
Write a C program to simulate the following CPU scheduling algorithms to find the turnaround time and
waiting time for the above problem.
a) Round Robin
b) Priority Scheduling
B. Learning Outcome:
After this lecture, the students will be able to learn about the fundamental concepts of CPU scheduling. Also,
they will be able to learn about different algorithms.
Activity List:
● The steps for each algorithm will be discussed in class.
● Students can use any programming language for implementation.
● Sample Inputs are shown in the Green boxes.
● In the blue box, students should write the appropriate output for each Algorithm.
Description:
To aim is to calculate the average waiting time. There will be a time slice, each process should be
executed within that time slice and if not it will go to the waiting state so first check whether the burst
time is less than the time slice. If it is less than it assign the waiting time to the sum of the total times. If
it is greater than the burst time then subtract the time slot from the actual burst time and increment it by
time-slot and the loop continues until all the processes are completed.
Algorithm:
Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue and time quantum (or) time slice
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time
Step 4: Calculate the no. of time slices for each process where No. of time slice for a process (n) = burst
time process (n)/time slice
18
Step 5: If the burst time is less than the time slice then the no. of time slices =1.
Step 6: Consider the ready queue is a circular Q, calculate
a) Waiting time for process (n) = waiting time of process(n-1)+ burst timeof process(n-1 ) + the
time difference in getting the CPU fromprocess(n-1)
b) Turnaround time for process(n) = waiting time of process(n) + burst time of process(n)+ the
time difference in getting CPU from process(n).
Step 7: Calculate
a) Average waiting time = Total waiting Time / Number of processes
b) Average Turnaround time = Total Turnaround Time / Number of process
Step 8: Stop the process
Priority scheduling:
Description:
To calculate the average waiting time in the priority algorithm, sort the burst times according to their
priorities and then calculate the average waiting time of the processes. The waiting time of each
process is obtained by summing up the burst times of all the previous processes.
Algorithm:
19
Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time
Step 4: Sort the ready queue according to the priority number.
Step 5: Set the waiting of the first process as `0` and its burst time as its turnaround time
Step 6: Arrange the processes based on process priority
Step 7: For each process in the Ready Q calculate
a) Waiting time(n)= waiting time (n-1) + Burst time (n-1)
b) Turnaround time (n)= waiting time(n)+Burst time(n)
Step 8: Calculate
a) Average waiting time = Total waiting Time / Number of processes
b) Average Turnaround time = Total Turnaround Time / Number of processes. Print the
results in an order.
Step9:Stop
Task:
The students will be assigned the Open ended Lab Task
20
Lab Task 05: Multi-Level Queue Scheduling
A. Overview:
Write a C program to simulate the multilevel queue scheduling algorithms to find the turnaround time and
waiting time.
B. Learning Outcome:
After this lecture, the students will be able to learn about the fundamental concepts of multilevel queue
scheduling. Also, they will be able to implement the algorithm.
Activity List:
● The steps for each algorithm will be discussed in class.
● Students can use any programming language for implementation.
● Sample Inputs are shown in the Green boxes.
● In the blue box, students should write the appropriate output for each Algorithm.
● Students are assigned with a project
Description
Multi-level queue scheduling algorithm is used in scenarios where the processes can be classified into
groups based on properties like process type, CPU time, IO access, memory size, etc. In a multi-level queue
scheduling algorithm, there will be 'n' number of queues, where 'n' is the number of groups the processes are
classified into. Each queue will be assigned a priority and will have its own scheduling algorithm like
round-robin scheduling or FCFS. For the process in a queue to execute, all the queues of priority higher than
it should be empty, meaning the process in those high priority queues should have completed its execution. In
this scheduling algorithm, once assigned to a queue, the process will not move to any other queues.
Algorithm:
All the processes in the system are divided into two categories – system processes and user processes.
System processes are to be given higher priority than user processes. System processes are added in Queue1
(Priority 1) and user processes are added in Queue2 (Priority 2).
Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue
Step 3: Create two queues, each with its own priority level.
Step 4: For each process, assign the process ID and accept the CPU burst time
Step 5: Assign each incoming process to the appropriate queue based on its priority level.
Step 6: Implement a scheduling algorithm for each queue, such as Round Robin, First-Come-First-Serve,
or Priority Scheduling.
21
Step 7: If all processes from Queue1 finish execution, then the processes from queue2 will be executed.
Step 8: Calculate
a) Average waiting time = Total waiting Time / Number of processes
Project Assignment:
1. The teacher defines the objective, requirements, deadlines, and evaluation criteria of the project.
This will help ensure that students understand what is expected of them and can work effectively
together.
2. Students create their own project groups. Each group contains a maximum of 3 members.
3. The teacher assigns a particular problem to students.
22
Lab Task 06: File allocation strategies
A. Overview:
Write a C program to simulate the following file allocation strategies:
a. Sequential
b. Indexed
B. Learning Outcome:
After this lecture, the students will be able to learn about the fundamental concepts of file allocation
strategies. Also, they will be able to implement the algorithm.
Activity List:
● The steps for each algorithm will be discussed in class.
● Students can use any programming language for implementation.
● Sample Inputs are shown in the Green boxes.
● In the blue box, students should write the appropriate output for each Algorithm.
Description
A file is a collection of data, usually stored on disk. As a logical entity, a file enables to divide data
into meaningful groups. As a physical entity, a file should be considered in terms of its organization. The term
"file organization" refers to the way in which data is stored in a file and, consequently, the method(s) by
which it can be accessed.
Algorithm:
Step 1: Start the program.
Step 2: Get the number of files.
Step 3: Get the memory requirement of each file.
Step 4: Allocate the required locations to each in sequential order. Randomly select a
location from available location s1= random(100);
a) Check whether the required locations are free from the selected location.
if(b[s1].flag==0){
for (j=s1;j<s1+p[i];j++){ if((b[j].flag)==0)count++;
23
}
if(count==p[i]) break;
}
b) Allocate and set flag=1 to the allocated locations.
for(s=s1;s<(s1+p[i]);s++) {
k[i][j]=s; j=j+1; b[s].bno=s; b[s].flag=1;
}
Step 5: Print the results file no, length, Blocks allocated.
Step 6: Stop the program
Algorithm:
24
b[q].fno=j;
r[i][j]=q;
Step 5: Print the results file no, length, Blocks allocated.
Step 6: Stop the program
25
Lab Task 07: Memory Allocation Techniques
A. Overview:
Write a program to simulate the following contiguous memory allocation techniques
a) Worst-fit b) Best-fit c) First-fit
B. Learning Outcome:
After this lecture, the students will be able to learn about the fundamental concepts of file allocation
strategies. Also, they will be able to implement the algorithm.
Activity List:
● The steps for each algorithm will be discussed in class.
● Students can use any programming language for implementation.
● Sample Inputs are shown in the Green boxes.
● In the blue box, students should write the appropriate output for each Algorithm.
Description
One of the simplest methods for memory allocation is to divide memory into several fixed-sized partitions.
Each partition may contain exactly one process. In this multiple-partition method, when a partition is free, a
process is selected from the input queue and is loaded into the free partition. When the process terminates, the
partition becomes available for another process. The operating system keeps a table indicating which parts of
memory are available and which are occupied. Finally, when a process arrives and needs memory, a memory
section large enough for this process is provided. When it is time to load or swap a process into main memory,
and if there is more than one free block of memory of sufficient size, then the operating system must decide
which free block to allocate. Best-fit strategy chooses the block that is closest in size to the request. First-fit
chooses the first available block that is large enough. Worst-fit chooses the largest available block.
Program
Worst-Fit
#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp;
static int bf[max],ff[max];
clrscr();
26
printf("\n\tMemory Management Scheme - First Fit");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];
if(temp>=0)
{
ff[i]=j;
break;
}
}
}
frag[i]=temp;
bf[ff[i]]=1;
}
printf("\nFile_no:\tFile_size :\tBlock_no:\tBlock_size:\tFragement");
for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}
BEST-FIT
Best Fit
27
#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,lowest=10000;
static int bf[max],ff[max];
clrscr();
28
FIRST-FIT
#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,highest=0;
static int bf[max],ff[max];
clrscr();
29
for(i=1;i<=nf;i++)
{
18
for(j=1;j<=nb;j++)
{
if(bf[j]!=1) //if bf[j] is not allocated
{
temp=b[j]-f[i];
if(temp>=0)
if(highest<temp)
{
ff[i]=j;
highest=temp;
}
}
}
frag[i]=highest;
bf[ff[i]]=1;
highest=0;
}
printf("\nFile_no:\tFile_size :\tBlock_no:\tBlock_size:\tFragement");
for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}
30
Lab Task 08: File Organization Techniques
A. Overview:
Write a C program to simulate the following file organization techniques
a) Single level directory
B. Learning Outcome:
After this lecture, the students will be able to learn about the fundamental concepts of file allocation
strategies. Also, they will be able to implement the algorithm.
Activity List:
● The steps for each algorithm will be discussed in class.
● Students can use any programming language for implementation.
● Sample Inputs are shown in the Green boxes.
● In the blue box, students should write the appropriate output for each Algorithm.
31
#include<stdio.h>
struct
{
char dname[10],fname[10][10]; int fcnt;
}dir;
void main()
{
int i,ch; char f[30]; clrscr();
dir.fcnt = 0;
printf("\nEnter name of directory -- ");
scanf("%s", dir.dname);
while(1)
{
printf("\n\n1. Create File\t2. Delete File\t3. Search File \n
4. Display Files\t5. Exit\nEnter your choice -- ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nEnter the name of the file -- "); scanf("%s",dir.fname[dir.fcnt]); dir.fcnt++;
break;
32
}
if(i==dir.fcnt)
printf("File %s not found",f);
break;
Case 4: if(dir.fcnt==0)
printf("\nDirectory Empty");
else
{
printf("\nThe Files are -- ");
for(i=0;i<dir.fcnt;i++)
printf("\t%s",dir.fname[i]);
}
break;
default: exit(0);
}
}
getch();
}
33
Lab Task 09: File Organization Techniques
A. Overview:
Write a C program to simulate the following file organization techniques
a) Two level directory
B. Learning Outcome:
After this lecture, the students will be able to learn about the fundamental concepts of file allocation
strategies. Also, they will be able to implement the algorithm.
Activity List:
● The steps for each algorithm will be discussed in class.
● Students can use any programming language for implementation.
● Sample Inputs are shown in the Green boxes.
● In the blue box, students should write the appropriate output for each Algorithm.
34
Step 10: if check lev==0||lev==1 (*root)->ftype=1; else(*root)->ftype=2;
(*root)->level=lev; (*root)->y=50+lev*5; (*root)->x=x; (*root)
->lx=lx; (*root)->rx=rx;
Step 11:for i=0&&i<5 increment i
(*root)->link[i]=NULL;
if check (*root)->ftype==1
Step 12: if check (lev==0||lev==1)
if check(*root)->level==0
print "how many users"
else print"how many files"
print (*root)->name
read (*root)->nc
Step 13:Then (*root)->nc=0; if check(*root)->nc==0 gap=rx-lx;
else gap=(rx-lx)/(*root)->nc;
Step 14:for i=0&&i<(*root)->nc increment i;
create(&((*root)->link[i]),lev+1,(*root)->name,
lx+gap*i,lx+gap*i+gap,lx+gap*i+gap/2); then
(*root)->nc=0;
Step 15: Initialize e display function Initialize i set textstyle(2,0,4); set
textjustify(1,1); set fillstyle(1,BLUE);
setcolor(14); step 13:if check root!=NULL
Step 16:for i=0&&i<root->nc increment i
line(root->x,root->y,root->link[i]->x,root->link[i]->y);
Step 17: if check root->ftype==1
bar3d(root->x-20,root->y-10,root->x+20,root->y+10,0,0);
else fill ellipse(root->x,root- >y,20,20);
out textxy(root->x,root->y,root->name);
Step 18:for i=0&&i<root->nc increment i display(root->link[i]);
Step 19:End
35
36
Lab Task 10: Bankers Algorithm for Deadlock Avoidance
A. Overview:
B. Write a C program to simulate Bankers algorithm for the purpose of deadlock avoidance.
C. Learning Outcome:
After this lecture, the students will be able to learn about the fundamental concepts of file allocation
strategies. Also, they will be able to implement the algorithm.
Activity List:
● The steps for each algorithm will be discussed in class.
● Students can use any programming language for implementation.
● Sample Inputs are shown in the Green boxes.
● In the blue box, students should write the appropriate output for each Algorithm.
Description
In a multiprogramming environment, several processes may compete for a finite number of resources. A
process requests resources; if the resources are not available at that time, the process enters a waiting state.
Sometimes, a waiting process is never again able to change state, because the resources it has requested are
held by other waiting processes. This situation is called a deadlock. Deadlock avoidance is one of the
techniques for handling deadlocks. This approach requires that the operating system be given in advance
additional information concerning which resources a process will request and use during its lifetime. With this
additional knowledge, it can decide for each request whether or not the process should wait. To decide
whether the current request can be satisfied or must be delayed, the system must consider the resources
currently available, the resources currently allocated to each process, and the future requests and releases of
each process. Banker’s algorithm is a deadlock avoidance algorithm that is applicable to a system with
multiple instances of each resource type.
Program
#include<stdio.h>
struct file
{
int all[10];
int max[10];
int need[10];
int flag;
37
};
void main()
{
struct file f[10];
int fl;
int i, j, k, p, b, n, r, g, cnt=0, id, newr;
int avail[10],seq[10];
clrscr();
printf("Enter number of processes -- ");
scanf("%d",&n);
printf("Enter number of resources -- ");
scanf("%d",&r);
for(i=0;i<n;i++)
{
printf("Enter details for P%d",i);
printf("\nEnter allocation\t -- \t");
for(j=0;j<r;j++)
scanf("%d",&f[i].all[j]);
printf("Enter Max\t\t -- \t");
for(j=0;j<r;j++)
scanf("%d",&f[i].max[j]);
f[i].flag=0;
}
printf("\nEnter Available Resources\t -- \t");
for(i=0;i<r;i++)
scanf("%d",&avail[i]);
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
f[i].need[j]=f[i].max[j]-f[i].all[j];
if(f[i].need[j]<0)
38
f[i].need[j]=0;
}
}
cnt=0;
fl=0;
while(cnt!=n)
{
g=0;
for(j=0;j<n;j++)
{
if(f[j].flag==0)
{
b=0;
for(p=0;p<r;p++)
{
if(avail[p]>=f[j].need[p])
b=b+1;
else
b=b-1;
}
if(b==r)
{
printf("\nP%d is visited",j);
seq[fl++]=j;
f[j].flag=1;
for(k=0;k<r;k++)
avail[k]=avail[k]+f[j].all[k];
cnt=cnt+1;
printf("(");
for(k=0;k<r;k++)
printf("%3d",avail[k]);
printf(")");
g=1;
}
}
}
if(g==0)
{
printf("\n REQUEST NOT GRANTED -- DEADLOCK OCCURRED");
printf("\n SYSTEM IS IN UNSAFE STATE");
goto y;
}
}
printf("\nSYSTEM IS IN SAFE STATE");
printf("\nThe Safe Sequence is -- (");
39
for(i=0;i<fl;i++)
printf("P%d ",seq[i]);
printf(")");
y: printf("\nProcess\t\tAllocation\t\tMax\t\t\tNeed\n");
for(i=0;i<n;i++)
{
printf("P%d\t",i);
for(j=0;j<r;j++)
30
printf("%6d",f[i].all[j]);
for(j=0;j<r;j++)
printf("%6d",f[i].max[j]);
for(j=0;j<r;j++)
printf("%6d",f[i].need[j]);
printf("\n");
}
getch();
}
INPUT
Enter number of processes – 5
Enter number of resources -- 3
Enter details for P0
Enter allocation -- 0 1 0
Enter Max -- 7 5 3
40
OUTPUT
P1 is visited( 5 3 2)
P3 is visited( 7 4 3)
P4 is visited( 7 4 5)
P0 is visited( 7 5 5)
P2 is visited( 10 5 7)
SYSTEM IS IN SAFE STATE
The Safe Sequence is -- (P1 P3 P4 P0 P2 )
41
Lab Task 11: Lab Final Exam
Overview:
This Lab is reserved for the Lab Final Exam.
42