OS Lab Manual
OS Lab Manual
OS Lab Manual
SCHOOL OF COMPUTING
3. Shell Programs
4. Process Creation
5. Multithreading
11.
Memory Allocation Techniques First-Best-Worst Fit
14 File Allocation-Sequential-Indexed
21CSC202J-Operating Systems Lab
Linux operating system can be installed as either dual OS in your system or you can
install through a virtual machine (VM).
Steps
1. Download VMware Player or Workstation recent version.
2. Download Ubuntu LTS recent version.
3. Install VM ware Player in your host machine.
4. Open VMware Workstation and click on "New Virtual Machine".
5. Select "Typical (recommended)" and click "Next".
6. Select "Installer disc image (ISO)", click "Browse" to select the Ubuntu ISO file,
click "Open" then "Next".
7. You have to type in "Full name", "User name" that must only consist of lowercase
and numbers then you must enter a password. After you finished, click "Next".
8. You can type in a different name in "Virtual machine name" or leave as is and select
an appropriate location to store the virtual machine by clicking on "Browse" that is
next to "Location" -- you should place it in a drive/partition that has at least 5GB of
free space. After you selected the location click "OK" then "Next".
9. In "Maximum disk size" per Ubuntu recommendations you should allocate at least 5GB
-- double is recommended to avoid running out of free space.
10. Select "Store virtual disk as a single file" for optimum performance and click "Next".
11. Click on "Customize" and go to "Memory" to allocate more RAM -- 1GB
should suffice, but more is always better if you can spare from the installed
RAM.
12. Go to "Processors" and select the "Number of processors" that for a normal
computer is 1 and "Number of cores per processor" that is 1 for single core, 2 for
dual core, 4 for quad core and so on -- this is to insure optimum performance of the
virtual machine.
13. Click "Close" then "Finish" to start the Ubuntu install process.
14. On the completion of installation, login to the system
© SRMIST -1-
21CSC202J-Operating Systems Lab
Press the power button on your system, and after few moments you see the Linux login
prompt. From the time you press the power button until the Linux login prompt appears, the
following sequence occurs. The following are the 6 high level stages of a typical Linux boot
process.
Power On
Kernel
Kernel executes /sbin/init
Init
Init executes runlevel programs
Login Process
Step 1.BIOS
BIOS stands for Basic Input/Output System
Performs some system integrity checks
Step 2. MBR
MBR stands for Master Boot Record.
It is located in the 1st sector of the bootable disk. Typically /dev/hda, or /dev/sda
MBR is less than 512 bytes in size. This has three components 1) primary boot loader info
in 1st 446 bytes 2) partition table info in next 64 bytes 3) mbr validation check in last 2
bytes.
It contains information about GRUB (or LILO in old systems).
So, in simple terms MBR loads and executes the GRUB boot loader.
© SRMIST -2-
21CSC202J-Operating Systems Lab
Step 3. GRUB
GRUB stands for Grand Unified Bootloader.
If you have multiple kernel images installed on your system, you can choose which one
to be executed.
GRUB displays a splash screen, waits for few seconds, if you don’t enter anything, it
loads the default kernel image as specified in the grub configuration file.
GRUB has the knowledge of the filesystem (the older Linux loader LILO didn’t
understand filesystem).
Grub configuration file is /boot/grub/grub.conf (/etc/grub.conf is a link to this). The
following is sample grub.conf of CentOS.
#boot=/dev/sda
default=0
timeout=5
splashimage=(hd0,0)/boot/grub/splash.xpm.gz
hiddenmenu
title CentOS(2.6.18-194.el5PAE)
root(hd0,0)
kernel/boot/vmlinuz-2.6.18-194.el5PAE ro root=LABEL=/
initrd /boot/initrd-2.6.18-194.el5PAE.img
As you notice from the above info, it contains kernel and initrd image.
So, in simple terms GRUB just loads and executes Kernel and initrd images.
Step 4. Kernel
Mounts the root file system as specified in the “root=” in grub.conf
Kernel executes the /sbin/init program
Since init was the 1st program to be executed by Linux Kernel, it has the process id
(PID) of 1. Do a ‘ps -ef | grep init’ and check the pid.
initrd stands for Initial RAM Disk.
initrd is used by kernel as temporary root file system until kernel is booted and the real
root file system is mounted. It also contains necessary drivers compiled inside, which
helps it to access the hard drive partitions, and other hardware.
Step 5. Init
Looks at the /etc/inittab file to decide the Linux run level.
Following are the available run levels
■ 0 – halt
■ 1 – Single user mode
■ 2 – Multiuser, without NFS
■ 3 – Full multiuser mode
■ 4 – unused
■ 5 – X11
■ 6 – reboot
Init identifies the default initlevel from /etc/inittab and uses that to load all appropriate
program.
© SRMIST -3-
21CSC202J-Operating Systems Lab
Execute ‘grep initdefault /etc/inittab’ on your system to identify the default run level
If you want to get into trouble, you can set the default run level to 0 or 6. Since you
know what 0 and 6 means, probably you might not do that.
Typically you would set the default run level to either 3 or 5.
Login Process
1. Users enter their username and password
2. The operating system confirms your name and password.
3. A "shell" is created for you based on your entry in the "/etc/passwd" file
4. You are "placed" in your "home"directory.
5. Start-up information is read from the file named "/etc/profile". This file is known as
the system login file. When every user logs in, they read the information in this file.
6. Additional information is read from the file named ".profile" that is located in your
"home" directory. This file is known as your personal login file.
© SRMIST -4-
21CSC202J-Operating Systems Lab
a) Basics
1. echo SRM ➔ to display the string SRM
2. clear ➔ to clear the screen
3. date ➔ to display the current date and time
4. cal 2003 ➔ to display the calendar for the year 2003
cal 6 2003 ➔ to display the calendar for the June-2003
5. passwd ➔ to change password
6. mv f1 f2 ➔ rename file f1 as f2
© SRMIST -1-
21CSC202J-Operating Systems Lab
3. ls [gpy]et ➔ list files whose first letter is any one of the character g, p
or y and followed by the word et
4. ls [a-d,l-m]ring ➔ list files whose first letter is any one of the character
from a to d and l to m and followed by the word ring.
e) I/O Redirection
1. Input redirection
wc –l < ex1 ➔ To find the number of lines of the file ‘ex1’
2. Output redirection
who > f2 ➔ the output of ‘who’ will be redirected to file f2
f) Piping
Syntax : Command1 | command2
head –6 f1 |tail –2 ➔ prints the 5th & 6th lines of the file f1.
g) Environment variables
1. echo $HOME ➔ display the path of the home directory
3. echo $PS2 ➔ display the second prompt string ( > symbol by default )
© SRMIST -2-
21CSC202J-Operating Systems Lab
h) File Permission
-- chmod command is used to change the access permission of a file.
Method-1
Syntax : chmod [ugo] [+/-] [ rwxa ] filename
Method-2
Syntax : chmod octnum file1
read, & execute permissions for the group members ie; 4+0+1 = 5
© SRMIST -3-
21CSC202J-Operating Systems Lab
FILTERS
1. cut
■ Used to cut characters or fileds from a file/input
■ By default, tab is the filed separator(delimiter). If the fileds of the files are separated by
any other character, we need to specify explicitly by –d option
2. grep
■ Used to search one or more files for a particular pattern.
3. sort
■ Used to sort the file in order
4. Uniq
■ Displays unique lines of a sorted file
Syntax : uniq filename
© SRMIST -1-
21CSC202J-Operating Systems Lab
5. diff
■ Used to differentiate two files
Syntax : diff f1 f2
compare two files f1 & f2 and prints all the lines that are differed between f1
& f2.
Q2. Write a command to display user-id of all the users in your system.
$
Q3. Write a command to check whether the user judith is available in your system or not.
(use grep)
$
Q4. Write a command to display the lines of the file f1 starts with SRM.
$
Q6. Write a command to display the unique lines of the sorted file f21. Also display the
number of occurrences of each line.
$
Q7. Write a command to display the lines that are common to the files f1 and f2.
$
© SRMIST -2-
21CSC202J-Operating Systems Lab
INSTALLING SOFTWARE
To Update the package repositories
sudo apt-get update
To update installed software
sudo apt-get upgrade
To install a package/software
sudo apt-get install <package-name>
To remove a package from the system
sudo apt-get remove <package-name>
To reinstall a package
sudo apt-get install <package-name> --reinstall
MANAGING USERS
Managing users is a critical aspect of server management.
In Ubuntu, the root user is disabled for safety.
Root access can be completed by using the sudo command by a user who is in the
“admin” group.
When you create a user during installation, that user is added automatically to the admin
group.
To add a user:
sudo adduser username
To disable a user:
sudo passwd -l username
To enable a user:
sudo passwd -u username
To delete a user:
sudo userdel –r username
To create a group:
sudo addgroup groupname
To delete a group:
sudo delgroup groupname
© SRMIST -3-
21CSC202J-Operating Systems Lab
Q11. Create a user ‘elias’. Login to the newly created user and exit.
Q12. Disable the user ‘elias’, try to login and enable again.
Verified by
Faculty In-charge Sign : Date :
© SRMIST -4-
21CSC202J-Operating Systems Lab
© SRMIST -1-
21CSC202J-Operating Systems Lab
$ vi ex31
echo Enter value for n
read n
sum=0
i=1
while [ $i –le $n ]
do
sum=$((sum+i))
i=$((i+2))
done
echo Sum is $sum
Output :
© SRMIST -2-
21CSC202J-Operating Systems Lab
Q2. Write a program to check whether the file has execute permission or not. If not, add the
permission.
$ vi ex32
Q3. Write a shell script to list only the name of sub directories in the present working
directory
$ vi ex33
Q4. Write a program to check all the files in the present working directory for a pattern
(passed through command line) and display the name of the file followed by a message
stating that the pattern is available or not available.
$ vi ex34
Verified by
Faculty In-charge Sign : Date :
© SRMIST -3-
Ex. No. 4 PROCESS CREATION using fork() and Date :
Usage of getpid(), getppid(), wait()
functions
Compilation of C Program
Step 1 : Open the terminal and edit your program and save with extension “.c”
Ex. nano test.c
Virtual fork
vfork() is similar to fork but both processes shares the same address space.
#include <stdio.h>
#include<unistd.h>
int main()
{
int a=5,b=10,pid;
printf("Before fork a=%d b=%d \n",a,b);
pid=fork();
if(pid==0)
{
a=a+1; b=b+1;
printf("In child a=%d b=%d \n",a,b);
}
else
{
sleep(1);
a=a-1; b=b-1;
printf("In Parent a=%d b=%d \n",a,b);
}
return 0;
}
Output :
Q2. Rewrite the program in Q1 using vfork() and write the output
#include <stdio.h>
#include<unistd.h>
int main()
{
fork();
fork();
fork();
printf(“SRMIST\n”);
return 0;
}
Output :
Q4. Complete the following program as described below :
The child process calculates the sum of odd numbers and the parent process calculate the
sum of even numbers up to the number ‘n’. Ensure the Parent process waits for the child
process to finish.
#include <stdio.h>
#include<unistd.h>
int main()
{
int pid,n,oddsum=0,evensum=0;
return 0;
}
Sample Output :
Enter the value of n 10
Sum of odd numbers 25
Sum of even numbers : 30
Q5. How many child processes are created for the following code?
Hint : Check with small values of ‘n’.
Output :
Q6. Write a program to print the Child process ID and Parent process ID in both Child
and Parent processes
#include <stdio.h>
#include<unistd.h>
int main()
{
return 0;
}
Sample Output:
In Child Process
Parent Process ID : 18
Child Process ID : 20
In Parent Process
Parent Process ID : 18
Child Process ID : 20
Q7. How many child processes are created for the following code?
#include <stdio.h>
#include<unistd.h>
int main()
{
fork();
fork()&&fork()||fork();
fork();
printf(“Yes ”);
return 0;
}
Output :
Web Reference:
https://www.geeksforgeeks.org/fork-system-call/
https://www.geeksforgeeks.org/getppid-getpid-linux/
https://www.geeksforgeeks.org/wait-system-call-c/
Ex.No.5 MULTI-THREADING
AIM:
Write a C program to demonstrate various thread related concepts.
Threads:
A thread is a path which is followed during a program’s execution. Majority of programs written now a
days run as a single thread. Let’s say, for example a program is not capable of reading keystrokes while
making drawings. These tasks cannot be executed by the program at the same time. This problem can
be solved through multitasking so that two or more tasks can be executed simultaneously.
Multitasking is of two types: Processor based and thread based. Processor based multitasking is totally
managed by the OS, however multitasking through multithreading can be controlled by the programmer
to some extent.
The concept of multi-threading needs proper understanding of these two terms – a process and a thread.
A process is a program being executed. A process can be further divided into independent units known
as threads.
A thread is like a small light-weight process within a process. Or we can say a collection of threads is
what is known as a process.
Why Multithreading? Threads are popular way to improve application through parallelism.
For example, in a browser, multiple tabs can be different threads. MS word uses multiple
threads, one thread to format the text, other thread to process inputs, etc.
Unlike Java, multithreading is not supported by the language standard. POSIX Threads (or Pthreads)
is a POSIX standard for threads. Implementation of pthread is available with gcc compiler.
We must include the pthread.h header file at the beginning of the script to use all the
functions of the pthreads library.
Create 3 threads, first one to find the sum of odd numbers; second one to find the sum of even
numbers; third one to find the sum of natural numbers;
This program also displays the list of odd/even numbers.
Complete the code snippet wherever applicable in the below program highlighted in red colour
font.
int je,jo,evensum=0,sumn=0,oddsum=0,evenarr[50],oddarr[50];
for(i=0;i<=n;i++)
{
if(logic to allow only odd numbers)
{Calculate sum of odd numbers only}
}
}
void *SumN(_________)
{
int i,n;
n=(int)threadid;
for(i=1;i<=n;i++)
{ Calculate sum of natural numbers only}
}
int main()
{
pthread_t threads[NUM_THREADS];
int i,t;
printf("Enter a number\n");
scanf("%d",&t);
for(i=0;i<NUM_THREADS;i++)
{
pthread_join(threads[i],NULL);
}
printf("The sum of first N natural numbers is %d\n", display the sum of natural numbers);
printf("The sum of first N even numbers is %d\n",display the sum of even numbers);
printf("The sum of first N odd numbers is %d\n",oddsum);
printf("The first N Even numbers are----\n");
Print all the Even numbers
printf("The first N Odd numbers are ----\n");
Print all the ODD numbers
pthread_exit(NULL);
}
Result:
Thus, the program has been executed successfully by creating three threads.
Ex. No. 6 Mutual Exclusion-Semaphore and Reader Writer Date :
Solution
Semaphore
Semaphore is used to implement process synchronization. This is to protect critical region
shared among multiples processes.
key ➔ semaphore id
nsems ➔ no. of semaphores in the semaphore array
semflg ➔ IPC_CREATE|0664 : to create a new semaphore
IPC_EXCL|IPC_CREAT|0664 : to create new semaphore and the
call fails if the semaphore already exists
To perform operations on the semaphore sets viz., allocating resources, waiting for the
resources or freeing the resources,
int semop(int semid, struct sembuf *semops, size_t nsemops)
#include<sys/ipc.h>
#include<sys/sem.h>
int main()
{
int pid,semid,val;
struct sembuf sop;
semid=semget((key_t)6,1,IPC_CREAT|0666);
pid=fork();
sop.sem_num=0;
sop.sem_op=0;
sop.sem_flg=0;
if (pid!=0)
{
sleep(1);
printf("The Parent waits for WAIT signal\n");
semop(semid,&sop,1);
printf("The Parent WAKED UP & doing her job\n");
sleep(10);
printf("Parent Over\n");
}
else
{
printf("The Child sets WAIT signal & doing her job\n");
semctl(semid,0,SETVAL,1);
sleep(10);
printf("The Child sets WAKE signal & finished her job\n");
semctl(semid,0,SETVAL,0);
printf("Child Over\n");
}
return 0;
}
Output :
POSIX SEMAPHORE
The POSIX system in Linux presents its own built-in semaphore library. To
use it, we have to include semaphore.h and compile the code by linking
with -lpthread - lrt
To initialize a semaphore
sem_init(sem_t *sem, int pshared, unsigned int
value);
Where,
sem : Specifies the semaphore to be initialized.
pshared : This argument specifies whether or not the newly
initialized semaphore is shared between processes/threads. A non-zero
value means the semaphore is shared between processes and a value of
zero means it is shared between threads.
value : Specifies the value to assign to the newly initialized semaphore.
To destroy a semaphore
sem_destroy(sem_t *mutex);
Q2. Program creates two threads: one to increment the value of a shared variable and
second to decrement the value of the shared variable. Both the threads make use of
semaphore variable so that only one of the threads is executing in its critical section.
Execute and write the output.
#include<pthread.h>
#include<stdio.h>
#include<semaphore.h>
#include<unistd.h>
void *fun1();
void *fun2();
int shared=1; //shared variable
sem_t s; //semaphore variable
int main()
{
sem_init(&s,0,1); //initialize semaphore variable - 1st argument is
//address of variable, 2nd is number of processes sharing semaphore,
//3rd argument is the initial value of semaphore variable
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, fun1, NULL);
sleep(1);
pthread_create(&thread2, NULL, fun2, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2,NULL);
printf("Final value of shared is %d\n",shared); //prints the last
//updated value of shared variable
}
void *fun1()
{
int x;
sem_wait(&s); //executes wait operation on s
x=shared;//thread1 reads value of shared variable
printf("Thread1 reads the value as %d\n",x);
x++; //thread1 increments its value
printf("Local updation by Thread1: %d\n",x);
sleep(1); //thread1 is preempted by thread 2
shared=x; //thread one updates the value of shared variable
printf("Value of shared variable updated by Thread1 is:
%d\n",shared);
sem_post(&s);
}
void *fun2()
{
int y;
sem_wait(&s);
y=shared;//thread2 reads value of shared variable
printf("Thread2 reads the value as %d\n",y);
y--; //thread2 increments its value
printf("Local updation by Thread2: %d\n",y);
sleep(1); //thread2 is preempted by thread 1
shared=y; //thread2 updates the value of shared variable
printf("Value of shared variable updated by Thread2 is:
%d\n",shared);
sem_post(&s);
}
The final value of the variable shared will be 1. When any one of the threads executes the
wait operation the value of “s” becomes zero. Hence the other thread (even if it
preempts the running thread) is not able to successfully execute the wait operation on
“s“. Thus, not able to read the inconsistent value of the shared variable. This ensures that
only one of the threads is running in its critical section at any given time.
Output:
Reader Writer Solution
In a reader-writer problem, multiple readers can read data from a shared resource, while only
one writer can write data to the resource. The challenge is to ensure that the readers do not
read data while the writer is writing, and the writer does not write data while the readers are
reading.
For example, consider a scenario where a database is being accessed by multiple users. The
users can read data from the database, but only one user can write data to the database at a
time. The challenge is to ensure that the users do not read data while the database is being
written to, and the writer does not write data while the users are reading.
Q3.
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
/*
This program provides a possible solution for first readers writers
problem using mutex and semaphore.
I have used 10 readers and 5 producers to demonstrate the solution.
You can always play with these values.
*/
sem_t wrt;
pthread_mutex_t mutex;
int cnt = 1;
int numreader = 0;
}
void *reader(void *rno)
{
// Reader acquire the lock before modifying numreader
pthread_mutex_lock(&mutex);
numreader++;
if(numreader == 1) {
sem_wait(&wrt); // If this id the first reader, then it will
block the writer
}
pthread_mutex_unlock(&mutex);
// Reading Section
printf("Reader %d: read cnt as %d\n",*((int *)rno),cnt);
int main()
{
pthread_t read[10],write[5];
pthread_mutex_init(&mutex, NULL);
sem_init(&wrt,0,1);
pthread_mutex_destroy(&mutex);
sem_destroy(&wrt);
return 0;
Output:
Verified by
Faculty In-charge Sign : Date :
Ex. No. 7 Dining Philosopher problem Date :
AIM:
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
#include<unistd.h>
sem_t room;
sem_t chopstick[5];
void * philosopher(void * num)
{
//Write coding for Main Philosopher thread
int main()
{
int i,a[5]; pthread_t tid[5];
sem_init(&room,0,4);
for(i=0;i<5;i++)
sem_init(&chopstick[i],0,1);
for(i=0;i<5;i++)
{ a[i]=i;
pthread_create(&tid[i],NULL,philosopher,(void *)&a[i]);
}
for(i=0;i<5;i++)
pthread_join(tid[i],NULL);
}
Output:
Verified by
Faculty In-charge Sign : Date :
Ex. No. 8 SCHEDULING ALGORITHMS Date :
FCFS-SJF
Given n processes with their burst times, the task is to find average waiting time and average
turn around time using FCFS scheduling algorithm. First in, first out (FIFO), also known as
first come, first served (FCFS), is the simplest scheduling algorithm. FIFO simply queues
processes in the order that they arrive in the ready queue.
In this, the process that comes first will be executed first and next process starts only after the
previous gets fully executed. Here we are considering that arrival time for all processes
is 0.
Turn Around Time: Time Difference between completion time and arrival time.
Turn Around Time = Completion Time – Arrival Time
Waiting Time(W.T): Time Difference between turn around time and burst time.
Waiting Time = Turn Around Time – Burst Time
Algorithm:
Step 1. Input the processes along with their burst time (bt).
Step 2. Find waiting time (wt) for all processes.
Step 3. As first process that comes need not to wait so
waiting time for process 1 will be 0 i.e. wt[0] = 0.
Step 4. Find waiting time for all other processes i.e. for
process i ->
wt[i] = bt[i-1] + wt[i-1]
Step 5. Find turnaround time = waiting_time + burst_time
for all processes.
Step 6. Find average waiting time = total_waiting_time / no_of_processes
Step 7. Similarly, find average turnaround time =
total_turn_around_time / no_of_processes.
#include <stdio.h>
//Write the program here
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 process previous or before to
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 Q, assign the process id and accept the CPU burst
time
Step 4: Start the Ready Q according 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
c) Average waiting time = Total waiting Time / Number of process
d) Average Turnaround time = Total Turnaround Time / Number of process Step 9:
Stop the process
#include <stdio.h>
//Write the program here
Verified by
Faculty In-charge Sign : Date :
Ex. No. 9 SCHEDULING ALGORITHMS Date :
Priority and Round Robin
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:
Step 1: Start the process
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 Step 8:
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 9: Calculate
c) Average waiting time = Total waiting Time / Number of process
d) Average Turnaround time = Total Turnaround Time / Number of process Print the
results
in an order.
Step10: Stop
#include <stdio.h>
//Write the program here
2. ROUND ROBIN:
AIM:
To simulate the CPU scheduling algorithm round-robin.
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:
#include <stdio.h>
//Write the program here
Verified by
Faculty In-charge Sign : Date :
Ex. No. 10 BANKERS ALGORITHM-DEAD LOCK Date :
AVOIDANCE
AIM:
To Simulate bankers algorithm for Dead Lock Avoidance (Banker‘s Algorithm)
DESCRIPTION:
Deadlock is a situation where in two or more competing actions are waiting f or the other to
finish, and thus neither ever does. When a new process enters a system, it must declare the
maximum number of instances of each resource type it needed. This number may exceed the
total number of resources in the system. When the user request a set of resources, the system
must determine whether the allocation of each resources will leave the system in safe state. If
it will the resources are allocation; otherwise the process must wait until some other process
release the resources.
Data structures
n-Number of process,
m-number of resource types.
Available: Available[j]=k, k – instance of resource type Rj is available.
Max: If max[i, j]=k, Pi may request at most k instances resource Rj.
Allocation: If Allocation [i, j]=k, Pi allocated to k instances of resource Rj
Need: If
Need[I, j]=k, Pi may need k more instances of resource type Rj, Need[I, j]=Max[I, j]-
Allocation[I, j];
Safety Algorithm
1. Work and Finish be the vector of length m and n respectively, Work=Available and
Finish[i] =False.
2. Find an i such that both
Finish[i] =False
Need<=Work If no such I
exists go to step 4.
3. work= work + Allocation, Finish[i] =True;
4. if Finish[1]=True for all I, then the system is in safe state.
Let Request i be request vector for the process Pi, If request i=[j]=k, then process Pi
wants k instances of resource type Rj.
If the resulting resource allocation state is safe, the transaction is completed and process
Pi is allocated its resources. However if the state is unsafe, the Pi must wait for Request i
and the old resource-allocation state is restored.
ALGORITHM:
#include <stdio.h>
//Write the program here
Verified by
Faculty In-charge Sign : Date :
Ex. No. 11 MEMORY ALLOCATION TECHNIQUES- Date :
FIRST-BEST-WORST FIT
AIM:
To Write a C program to simulate the following contiguous memory allocation
techniques
a) Worst-fit b) Best-fit c) First-fit
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.
Q1. Write a program to simulate First, Best and Worst fit memory allocation techniques
algorithm
#include <stdio.h>
//Write the program here
Verified by
Faculty In-charge Sign : Date :
Ex. No. 12 PAGE REPLACEMENT ALGORITHMS Date :
FIFO- LRU - LFU
DESCRIPTION:
Page replacement algorithms are an important part of virtual memory management and it
helps the OS to decide which memory page can be moved out making space for the currently
needed page. However, the ultimate objective of all page replacement algorithms is to reduce
the number of page faults.
FIFO-This is the simplest page replacement algorithm. In this algorithm, the operating
system keeps track of all pages in the memory in a queue, the oldest page is in the front of the
queue. When a page needs to be replaced page in the front of the queue is selected for
removal.
LRU-The LRU stands for the Least Recently Used. It keeps track of page usage in the
memory over a short period of time. It works on the concept that pages that have been highly
used in the past are likely to be significantly used again in the future. It removes the page that
has not been utilized in the memory for the longest time. LRU is the most widely used
algorithm because it provides fewer page faults than the other methods.
The LFU page replacement algorithm stands for the Least Frequently Used. In the LFU
page replacement algorithm, the page with the least visits in a given period of time is
removed. It replaces the least frequently used pages. If the frequency of pages remains
constant, the page that comes first is replaced first.
Q1. Write a program to simulate FIFO, LRU and LFU page replacement techniques
algorithm
#include <stdio.h>
//Write the program here
Verified by
Faculty In-charge Sign : Date :
Ex. No. 13 DISK SCHEDULING ALGORITHMS Date :
FCFS-SCAN-C-SCAN
AIM:
To Write a C program to simulate disk scheduling algorithms
a) FCFS b) SCAN c) C-SCAN
DESCRIPTION
One of the responsibilities of the operating system is to use the hardware efficiently. For the
disk drives, meeting this responsibility entails having fast access time and large disk bandwidth.
Both the access time and the bandwidth can be improved by managing the order in which disk
I/O requests are serviced which is called as disk scheduling. The simplest form of disk
scheduling is, of course, the first-come, first-served (FCFS) algorithm. This algorithm is
intrinsically fair, but it generally does not provide the fastest service. In the SCAN algorithm,
the disk arm starts at one end, and moves towards the other end, servicing requests as it reaches
each cylinder, until it gets to the other end of the disk. At the other end, the direction of head
movement is reversed, and servicing continues. The head continuously scans back and forth
across the disk. C-SCAN is a variant of SCAN designed to provide a more uniform wait time.
Like SCAN, C-SCAN moves the head from one end of the disk to the other, servicing requests
along the way. When the head reaches the other end, however, it immediately returns to the
beginning of the disk without servicing any requests on the return trip
Q1. Write a program to simulate disk scheduling algorithms FCFS-SCAN and C-SCAN
#include <stdio.h>
//Write the program here
Verified by
Faculty In-charge Sign : Date :
Ex. No. 14 FILE ALLOCATION STRATEGIES Date :
SEQUENTIAL and INDEXED
A) SEQUENTIAL:
AIM: To write a C program for implementing sequential file allocation method
DESCRIPTION:
The most common form of file structure is the sequential file in this type of file, a fixed
format is used for records. All records (of the system) have the same length, consisting
of the same number of fixed length fields in a particular order because the length and
position of each field are known, only the values of fields need to be stored, the field
name and length for each field are attributes of the file structure.
ALGORITHM:
B) INDEXED:
AIM:
DESCRIPTION:
In the chained method file allocation table contains a field which points to starting block of
memory. From it for each bloc a pointer is kept to next successive block. Hence, there is no
external fragmentation.
ALGORITHM:
q=random(100);
{
if(b[q].flag==0)
b[q].flag=1;
b[q].fno=j;
r[i][j]=q;
Step 5: Print the results file no, length ,Blocks
allocated.
Step 6: Stop the program
#include <stdio.h>
//Write the program here
Verified by
Faculty In-charge Sign : Date :