OPERATING SYSTEMS
LABORATORY MANUAL
BCA(R22)
(II YEAR – I SEM)
(2023‐2026)
DEPARTMENT OF IT&CA
Experiment-1
Basic Ubuntu Commands
What are the basic commands of Ubuntu
This section contains some basic commands of Ubuntu, so let us start and
discuss them one by one. Firstly, you must open the terminal in Ubuntu; press “ctrl+alt+t”
from your keyboard to open the terminal.
Command 1: pwd
This command refers to the present working directory in which you are operating; in
simpler words, in which your terminal is open. To check PWD, execute the pwd keyword in
your terminal and hit enter; the command of PWD is written below along with the result of
that command.
Command 2: dir
The dir command is used to print (on the terminal) all the available directories in the
present working directory:
Command 3: ls
This command is used to list down all the directories and files inside the present
working directory (or you can give the path of a specific directory);
Command 4: cd
One of the most used commands of Ubuntu; you can change the directories in the
terminal using the “cd” command.
Command 5: touch
This Ubuntu command can be used to create a new file as well one can use it to
change the timestamp of any file; the command given below will create a new text time in
pwd:
Command 6: cat
This command is used to show the content of any file: you can use this command to
save the content of multiples files to one file:
Command 7: mkdir
The above-mentioned command will make a directory in your pwd; for example, the
following command will make the directory “new” in pwd.
Command 8: rm
This remove command is used to remove the specific file from a directory. you can
remove the empty directory,
Command 9: cp
The cp command will help you to copy any file or folder to any directory. If you want
to copy the complete folder, then.
Command 10: head
This command helps you to get the first ten lines of a text file; for instance,
Command 11: tail
The tail command is used to get the last ten lines of the text file.
Command 12: uname
You can use the command to get the release number, version of Linux, and much
more. The “-a” flag is used to get detailed information.
Command 13: wget
You can use the wget command to download the content from the internet.
Command 14: history
The history command shows the list of commands (with numeric numbers) executed:
Command 15: zip or unzip
To convert your files to zip archive; you can get help by using the “gzip” command;
moreover, a zipped file can be unzipped using the “gunzip” command
Command 16:
• clear – clear screen
Command 17: Time and Date commands
date – show current date and time
sleep – wait for a given number of seconds
uptime – find out how long the system has been
Command 18: Unix users’ commands
These commands allow you to get basic information about Unix users in your
environment
• whoami – show your username
• id – print user identity
• groups – show which groups user belongs to
• passwd – change user password
• who – find out who is logged into the system
• last – show history of logins into the system
Experiment-2
Basic C Programs in Ubuntu
C program for implementation of FCFS
// scheduling
#include
// Function to find the waiting time for all
// processes
void findWaitingTime(int processes[], int n, int bt[], int wt[])
// waiting time for first process is 0
wt[0] = 0;
// calculating waiting time
for (int i = 1; i < n ; i++ )
wt[i] = bt[i-1] + wt[i-1] ;
// Function to calculate turn around time
void findTurnAroundTime( int processes[], int n, int bt[], int wt[], int tat[])
// calculating turnaround time by adding
// bt[i] + wt[i]
for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i];
//Function to calculate average time
void findavgTime( int processes[], int n, int bt[])
int wt[n], tat[n], total_wt = 0, total_tat = 0;
//Function to find waiting time of all processes findWaitingTime(processes, n, bt, wt);
//Function to find turn around time for all processes findTurnAroundTime(processes, n, bt,
wt, tat);
//Display processes along with all details
printf("Processes Burst time Waiting time Turn around time\n");
// Calculate total waiting time and total turn
// around time
for (int i=0; i; i++)
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
printf(" %d ",(i+1));
printf(" %d ", bt[i] );
printf(" %d",wt[i] );
printf(" %d\n",tat[i] );
float s=(float)total_wt / (float)n;
float t=(float)total_tat / (float)n;
printf("Average waiting time = %f",s);
printf("\n");
printf("Average turn around time = %f ",t);
// Driver code
int main() {
//process id's
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];
//Burst time of all processes
int burst_time[] = {10, 5, 8};
findavgTime(processes, n, burst_time);
return 0;
Output:
Processes Burst time Waiting time Turn around time //The Output is Wrong please correct it
1 10 0 10
2 5 10 15
3 8 15 23
Average waiting time = 8.33333
Average turn around time = 16
Shortest Job First Scheduling
SOURCE CODE :
#include<stdio.h>
#include<conio.h>
main()
int p[20], bt[20], wt[20], tat[20], i, k, n, temp; float wtavg,
tatavg;
clrscr();
printf("\nEnter the number of processes -- ");
scanf("%d", &n);
for(i=0;i<n;i++)
p[i]=i;
printf("Enter Burst Time for Process %d -- ", i);
scanf("%d", &bt[i]);
for(i=0;i<n;i++)
for(k=i+1;k<n;k++)
if(bt[i]>bt[k])
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;
temp=p[i];
p[i]=p[k];
p[k]=temp;
wt[0] = wtavg = 0;
tat[0] = tatavg = bt[0]; for(i=1;i<n;i++)
wt[i] = wt[i-1] +bt[i-1];
tat[i] = tat[i-1] +bt[i];
wtavg = wtavg + wt[i];
tatavg = tatavg + tat[i];
}
printf("\n\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", p[i], bt[i], wt[i], tat[i]);
printf("\nAverage Waiting Time -- %f", wtavg/n);
printf("\nAverage Turnaround Time -- %f", tatavg/n); getch();}
INPUT
Enter the number of processes -- 4
Enter Burst Time for Process 0 -- 6
Enter Burst Time for Process 1 -- 8
Enter Burst Time for Process 2 -- 7
Enter Burst Time for Process 3 -- 3
OUTPUT
PROCESS BURST
TIME
WAITING
TIME
TURNARO
UND TIME
P3 3 0 3
P0 6 3 9
P2 7 9 16
P1 8 16 24
Average Waiting Time -- 7.000000
Average Turnaround Time -- 13.000000
C). ROUND ROBIN:
SOURCE CODE
#include<stdio.h>
main()
int
i,j,n,bu[10],wa[10],tat[10],t,ct[10],max;
float awt=0,att=0,temp=0;
clrscr();
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]);
getch();}
INPUT:
Enter the no of processes – 3
Enter Burst Time for process 1 – 24
Enter Burst Time for process 2 -- 3
Enter Burst Time for process 3 – 3
Enter the size of time slice – 3
OUTPUT:
PROCESS
BURST TIME
24
WAITING TIME TURNAROUNDTIME
30
The Average Turnaround time is – 15.666667 The
Average Waiting time is ------------ 5.666667
D). PRIORITY:
SOURCE CODE:
#include<stdio.h>
main()
int p[20],bt[20],pri[20], wt[20],tat[20],i, k, n, temp; float wtavg,
tatavg;
clrscr();
printf("Enter the number of processes --- ");
scanf("%d",&n);
for(i=0;i<n;i++){
p[i] = i;
printf("Enter the Burst Time & Priority of Process %d --- ",i); scanf("%d
%d",&bt[i], &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;
wtavg = wt[0] = 0;
tatavg = tat[0] = bt[0];
for(i=1;i<n;i++)
wt[i] = wt[i-1] + bt[i-1];
tat[i] = tat[i-1] + bt[i];
wtavg = wtavg + wt[i];
tatavg = tatavg + tat[i];
printf("\nPROCESS\t\tPRIORITY\tBURST TIME\tWAITING TIME\tTURNAROUND
TIME");
for(i=0;i<n;i++)
printf("\n%d \t\t %d \t\t %d \t\t %d \t\t %d ",p[i],pri[i],bt[i],wt[i],tat[i]);
printf("\nAverage Waiting Time is --- %f",wtavg/n); printf("\nAverage
Turnaround Time is --- %f",tatavg/n);
getch();}
INPUT
Enter the number of processes -- 5
Enter the Burst Time & Priority of Process 0 --- 10 3
Enter the Burst Time & Priority of Process 1 --- 1 1
Enter the Burst Time & Priority of Process 2 --- 2 4
Enter the Burst Time & Priority of Process 3 --- 1 5
Enter the Burst Time & Priority of Process 4 --- 5 2
OUTPUT
PROCESS PRIORITY BURST TIME WAITIN
G TIME
TURNARO
UND TIME
11101
42516
0 3 10 6 16
2 4 2 16 18
3 5 1 18 19
Average Waiting Time is --- 8.200000
Average Turnaround Time is --- 12.000000
EXPERIMENT.NO 3
Basic Shell programs
1.write Hello world program using shell script?
#!/bin/bash
echo "Hello, World!"
2.Add two numbers using Shell Script?
#!/bin/bash
echo "Enter first number: "
read a
echo "Enter second number: "
read b
sum=$((a + b))
echo "The sum of $a and $b is: $sum"
3.Write a Program to swap two numbers Using Shell Script?
#!/bin/bash
echo "Enter first number: "
read a
echo "Enter second number: "
read b
echo "Before swapping: a=$a, b=$b"
temp=$a
a=$b
b=$temp
echo "After swapping: a=$a, b=$b"
4.Write Program to Find Armstrong number using Shell Script?
#!/bin/bash
echo "Enter a number: "
read num
temp=$num
sum=0
while [ $temp -gt 0 ]
do
digit=$((temp % 10))
sum=$((sum + digit * digit * digit))
temp=$((temp / 10))
done
if [ $sum -eq $num ]; then
echo "$num is an Armstrong number"
else
echo "$num is not an Armstrong number"
fi
5.Fibonacci Series Program using Shell Script?
#!/bin/bash
echo "Enter the number of terms: "
read n
a=0
b=1
echo "Fibonacci Series: "
for (( i=0; i<n; i++ ))
do
echo -n "$a "
next=$((a + b))
a=$b
b=$next
done
echo
6.Factorial Program using Shell Script?
#!/bin/bash
echo "Enter a number: "
read n
fact=1
for (( i=1; i<=n; i++ ))
do
fact=$((fact * i))
done
echo "Factorial of $n is: $fact"
7.Palindrome Program using Shell Script?
#!/bin/bash
echo "Enter a number: "
read num
temp=$num
rev=0
while [ $temp -gt 0 ]
do
digit=$((temp % 10))
rev=$((rev * 10 + digit))
temp=$((temp / 10))
done
if [ $rev -eq $num ]; then
echo "$num is a palindrome"
else
echo "$num is not a palindrome"
fi
8.Perfect number using shell Script?
#!/bin/bash
echo "Enter a number: "
read num
sum=0
for (( i=1; i<num; i++ ))
do
if [ $((num % i)) -eq 0 ]; then
sum=$((sum + i))
fi
done
if [ $sum -eq $num ]; then
echo "$num is a perfect number"
else
echo "$num is not a perfect number"
Fi
Experiment-4
FCFS&SJF in shell script and c
#!/bin/bash
echo "Enter the number of processes:"
read n
# Initialize arrays for storing process data
declare -a processId
declare -a burstTime
declare -a waitingTime
declare -a turnaroundTime
# Read process burst times
for ((i = 0; i < n; i++)); do
echo "Enter burst time for process $((i + 1)):"
read burstTime[$i]
processId[$i]=$((i + 1))
done
# Calculate waiting time
waitingTime[0]=0
for ((i = 1; i < n; i++)); do
waitingTime[$i]=$((waitingTime[i - 1] + burstTime[i - 1]))
done
# Calculate turnaround time
for ((i = 0; i < n; i++)); do
turnaroundTime[$i]=$((waitingTime[i] + burstTime[i]))
done
# Display process info and calculate averages
echo -e "\nProcess ID\tBurst Time\tWaiting Time\tTurnaround Time"
totalWaitingTime=0
totalTurnaroundTime=0
for ((i = 0; i < n; i++)); do
echo -e "${processId[$i]}\t\t${burstTime[$i]}\t\t${waitingTime[$i]}\t\t$
{turnaroundTime[$i]}"
totalWaitingTime=$((totalWaitingTime + waitingTime[i]))
totalTurnaroundTime=$((totalTurnaroundTime + turnaroundTime[i]))
done
# Calculate and display average waiting and turnaround time
averageWaitingTime=$(echo "scale=2; $totalWaitingTime / $n" | bc)
averageTurnaroundTime=$(echo "scale=2; $totalTurnaroundTime / $n" | bc)
echo -e "\nAverage Waiting Time: $averageWaitingTime"
echo "Average Turnaround Time: $averageTurnaroundTime"
SJF
#!/bin/bash
echo "Enter the number of processes:"
read n
# Initialize arrays for storing process data
declare -a processId
declare -a burstTime
declare -a waitingTime
declare -a turnaroundTime
# Read process burst times
for ((i = 0; i < n; i++)); do
echo "Enter burst time for process $((i + 1)):"
read burstTime[$i]
processId[$i]=$((i + 1))
done
# Sort the processes based on burst time (ascending order)
for ((i = 0; i < n - 1; i++)); do
for ((j = i + 1; j < n; j++)); do
if [ ${burstTime[$i]} -gt ${burstTime[$j]} ]; then
# Swap burst time
temp=${burstTime[$i]}
burstTime[$i]=${burstTime[$j]}
burstTime[$j]=$temp
# Swap process ID
temp=${processId[$i]}
processId[$i]=${processId[$j]}
processId[$j]=$temp
fi
done
done
# Calculate waiting time
waitingTime[0]=0
for ((i = 1; i < n; i++)); do
waitingTime[$i]=$((waitingTime[i - 1] + burstTime[i - 1]))
done
# Calculate turnaround time
for ((i = 0; i < n; i++)); do
turnaroundTime[$i]=$((waitingTime[i] + burstTime[i]))
done
# Display process info and calculate averages
echo -e "\nProcess ID\tBurst Time\tWaiting Time\tTurnaround Time"
totalWaitingTime=0
totalTurnaroundTime=0
for ((i = 0; i < n; i++)); do
echo -e "${processId[$i]}\t\t${burstTime[$i]}\t\t${waitingTime[$i]}\t\t$
{turnaroundTime[$i]}"
totalWaitingTime=$((totalWaitingTime + waitingTime[i]))
totalTurnaroundTime=$((totalTurnaroundTime + turnaroundTime[i]))
done
# Calculate and display average waiting and turnaround time
averageWaitingTime=$(echo "scale=2; $totalWaitingTime / $n" | bc)
averageTurnaroundTime=$(echo "scale=2; $totalTurnaroundTime / $n" | bc)
echo -e "\nAverage Waiting Time: $averageWaitingTime"
echo "Average Turnaround Time: $averageTurnaroundTime"
Experiment-5
PRIORITY&ROUND ROBIN in c and shell script
PRIORITY
#!/bin/bash
echo "Enter the number of processes:"
read n
declare -a processId
declare -a burstTime
declare -a priority
declare -a waitingTime
declare -a turnaroundTime
# Read process burst times and priority
for ((i = 0; i < n; i++)); do
echo "Enter burst time for process $((i + 1)):"
read burstTime[$i]
echo "Enter priority for process $((i + 1)) (Lower number means higher priority):"
read priority[$i]
processId[$i]=$((i + 1))
done
# Sort processes based on priority (ascending order)
for ((i = 0; i < n - 1; i++)); do
for ((j = i + 1; j < n; j++)); do
if [ ${priority[$i]} -gt ${priority[$j]} ]; then
# Swap burst time
temp=${burstTime[$i]}
burstTime[$i]=${burstTime[$j]}
burstTime[$j]=$temp
# Swap priority
temp=${priority[$i]}
priority[$i]=${priority[$j]}
priority[$j]=$temp
# Swap process ID
temp=${processId[$i]}
processId[$i]=${processId[$j]}
processId[$j]=$temp
fi
done
done
# Calculate waiting time
waitingTime[0]=0
for ((i = 1; i < n; i++)); do
waitingTime[$i]=$((waitingTime[i - 1] + burstTime[i - 1]))
done
# Calculate turnaround time
for ((i = 0; i < n; i++)); do
turnaroundTime[$i]=$((waitingTime[i] + burstTime[i]))
done
# Display process info and calculate averages
echo -e "\nProcess ID\tBurst Time\tPriority\tWaiting Time\tTurnaround Time"
totalWaitingTime=0
totalTurnaroundTime=0
for ((i = 0; i < n; i++)); do
echo -e "${processId[$i]}\t\t${burstTime[$i]}\t\t${priority[$i]}\t\t${waitingTime[$i]}\t\t$
{turnaroundTime[$i]}"
totalWaitingTime=$((totalWaitingTime + waitingTime[i]))
totalTurnaroundTime=$((totalTurnaroundTime + turnaroundTime[i]))
done
# Calculate and display average waiting and turnaround time
averageWaitingTime=$(echo "scale=2; $totalWaitingTime / $n" | bc)
averageTurnaroundTime=$(echo "scale=2; $totalTurnaroundTime / $n" | bc)
echo -e "\nAverage Waiting Time: $averageWaitingTime"
echo "Average Turnaround Time: $averageTurnaroundTime"
ROUND ROBIN
#!/bin/bash
echo "Enter the number of processes:"
read n
# Initialize arrays for storing process data
declare -a processId
declare -a burstTime
declare -a remainingTime
declare -a waitingTime
declare -a turnaroundTime
echo "Enter the time quantum:"
read timeQuantum
# Read process burst times
for ((i = 0; i < n; i++)); do
echo "Enter burst time for process $((i + 1)):"
read burstTime[$i]
remainingTime[$i]=${burstTime[$i]}
processId[$i]=$((i + 1))
waitingTime[$i]=0
turnaroundTime[$i]=0
done
# Initialize time variables
currentTime=0
completedProcesses=0
# Round Robin Scheduling
while [ $completedProcesses -lt $n ]; do
for ((i = 0; i < n; i++)); do
if [ ${remainingTime[$i]} -gt 0 ]; then
if [ ${remainingTime[$i]} -gt $timeQuantum ]; then
currentTime=$((currentTime + timeQuantum))
remainingTime[$i]=$((remainingTime[$i] - timeQuantum))
else
currentTime=$((currentTime + remainingTime[$i]))
waitingTime[$i]=$((currentTime - burstTime[$i]))
remainingTime[$i]=0
turnaroundTime[$i]=$((waitingTime[$i] + burstTime[$i]))
completedProcesses=$((completedProcesses + 1))
fi
fi
done
done
# Display process info and calculate averages
echo -e "\nProcess ID\tBurst Time\tWaiting Time\tTurnaround Time"
totalWaitingTime=0
totalTurnaroundTime=0
for ((i = 0; i < n; i++)); do
echo -e "${processId[$i]}\t\t${burstTime[$i]}\t\t${waitingTime[$i]}\t\t$
{turnaroundTime[$i]}"
totalWaitingTime=$((totalWaitingTime + waitingTime[i]))
totalTurnaroundTime=$((totalTurnaroundTime + turnaroundTime[i]))
done
# Calculate and display average waiting and turnaround time
averageWaitingTime=$(echo "scale=2; $totalWaitingTime / $n" | bc)
averageTurnaroundTime=$(echo "scale=2; $totalTurnaroundTime / $n" | bc)
echo -e "\nAverage Waiting Time: $averageWaitingTime"
echo "Average Turnaround Time: $averageTurnaroundTime"
Experiment-6
Memory allocation techniques
MEMORY ALLOCATION TECHNIQUES
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.
PROGRAM
FIRST-FIT
#include<stdio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp;
static int bf[max],ff[max];
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]);
Page 25
}
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]);
}
INPUT
Enter the number of blocks: 3
Enter the number of files: 2
Enter the size of the blocks:-
Block 1: 5
Block 2: 2
Block 3: 7
Enter the size of the files:-
File 1: 1
File 2: 4
OUTPUT
File No File Size Block No Block Size Fragment
1 1 1 5 4
2 4 3 7 3
BEST-FIT
#include<stdio.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];
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)
if(lowest>temp)
{
ff[i]=j;
lowest=temp;
}
}}
frag[i]=lowest; bf[ff[i]]=1; lowest=10000;
}
printf("\nFile No\tFile Size \tBlock No\tBlock
Size\tFragment"); for(i=1;i<=nf && ff[i]!=0;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]);
}
INPUT
Enter the number of blocks: 3
Enter the number of files: 2
Enter the size of the blocks:-
Block 1: 5
Block 2: 2
Block 3: 7
Enter the size of the files:-
File 1: 1
File 2: 4
OUTPUT
File No File Size Block No Block Size Fragment
1 1 2 2 1
2 4 1 5 1
WORST-FIT
#include<stdio.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];
printf("\n\tMemory Management Scheme - Worst 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) //if bf[j] is not allocated
{
temp=b[j]-f[i];
if(temp>=0)
if(highest<temp)
{
}
}
frag[i]=highest; bf[ff[i]]=1; highest=0;
}
ff[i]=j; highest=temp;
}
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]);
}
INPUT
Enter the number of blocks: 3
Enter the number of files: 2
Enter the size of the blocks:-
Block 1: 5
Block 2: 2
Block 3: 7
Enter the size of the files:-
File 1: 1
File 2: 4
OUTPUT
File No File Size Block No Block Size Fragment
1 1 3 7 6
2 4 1 5 1
Experiment-7
Bankers algorithm
#include <stdio.h>
void calculateNeed(int need[][10], int max[][10], int allocation[][10], int n, int m) {
// Calculate the need matrix
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
need[i][j] = max[i][j] - allocation[i][j];
}
int checkSafety(int processes[], int avail[], int max[][10], int allocation[][10], int n, int m) {
int need[10][10], finish[10], safeSeq[10], work[10];
calculateNeed(need, max, allocation, n, m);
// Initialize finish array and work array
for (int i = 0; i < n; i++)
finish[i] = 0;
for (int i = 0; i < m; i++)
work[i] = avail[i];
int count = 0; // Count of processes that are included in safe sequence
while (count < n) {
int found = 0;
for (int p = 0; p < n; p++) {
// If a process is not finished and its need can be satisfied with available resources
if (finish[p] == 0) {
int j;
for (j = 0; j < m; j++)
if (need[p][j] > work[j])
break;
// If all needs are satisfied
if (j == m) {
// Update the available resources
for (int k = 0; k < m; k++)
work[k] += allocation[p][k];
// Add this process to the safe sequence
safeSeq[count++] = p;
finish[p] = 1;
found = 1;
}
}
}
// If no process could be allocated
if (found == 0) {
printf("System is not in a safe state\n");
return 0;
}
}
// If system is in a safe state, print the safe sequence
printf("System is in a safe state.\nSafe sequence is: ");
for (int i = 0; i < n; i++)
printf("%d ", safeSeq[i]);
printf("\n");
return 1;
}
int main() {
int n, m, i, j;
printf("Enter the number of processes: ");
scanf("%d", &n);
printf("Enter the number of resource types: ");
scanf("%d", &m);
int processes[n], avail[m], max[n][10], allocation[n][10];
// Enter the available resources
printf("Enter the available resources for each type: ");
for (i = 0; i < m; i++)
scanf("%d", &avail[i]);
// Enter the maximum demand of each process for each resource type
printf("Enter the maximum matrix:\n");
for (i = 0; i < n; i++) {
printf("For process %d: ", i);
for (j = 0; j < m; j++)
scanf("%d", &max[i][j]);
}
// Enter the allocation matrix
printf("Enter the allocation matrix:\n");
for (i = 0; i < n; i++) {
printf("For process %d: ", i);
for (j = 0; j < m; j++)
scanf("%d", &allocation[i][j]);
}
// Check if the system is in a safe state
checkSafety(processes, avail, max, allocation, n, m);
return 0;
}
Output:
Enter the number of processes: 5
Enter the number of resource types: 3
Enter the available resources for each type: 3 3 2
Enter the maximum matrix:
For process 0: 7 5 3
For process 1: 3 2 2
For process 2: 9 0 2
For process 3: 2 2 2
For process 4: 4 3 3
Enter the allocation matrix:
For process 0: 0 1 0
For process 1: 2 0 0
For process 2: 3 0 2
For process 3: 2 1 1
For process 4: 0 0 2
Experiment-8
Dining-Philosophers Problem and Producer Consumer Problem
Dining-philosphers:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define N 5 // Number of philosophers
#define THINKING 0
#define HUNGRY 1
#define EATING 2
#define LEFT (philosopher_number + N - 1) % N // Index of left neighbor
#define RIGHT (philosopher_number + 1) % N // Index of right neighbor
int state[N]; // Array to keep track of states of philosophers
int philosophers[N] = {0, 1, 2, 3, 4}; // Array to hold philosopher indices
sem_t mutex; // Semaphore to control access to critical section
sem_t S[N]; // Array of semaphores, one for each philosopher
void test(int philosopher_number) {
if (state[philosopher_number] == HUNGRY &&
state[LEFT] != EATING &&
state[RIGHT] != EATING) {
// State that eating can take place
state[philosopher_number] = EATING;
printf("Philosopher %d takes fork %d and %d\n",
philosopher_number + 1, LEFT + 1, philosopher_number + 1);
printf("Philosopher %d is Eating\n", philosopher_number + 1);
// Signal the philosopher that it's ok to eat
sem_post(&S[philosopher_number]);
}
}
// Function to pick up forks
void take_fork(int philosopher_number) {
sem_wait(&mutex); // Enter critical section
state[philosopher_number] = HUNGRY;
printf("Philosopher %d is Hungry\n", philosopher_number + 1);
// Try to acquire fork if neighbors are not eating
test(philosopher_number);
sem_post(&mutex); // Exit critical section
// Wait until the philosopher can eat
sem_wait(&S[philosopher_number]);
sleep(1);
}
// Function to put down forks
void put_fork(int philosopher_number) {
sem_wait(&mutex); // Enter critical section
state[philosopher_number] = THINKING;
printf("Philosopher %d putting fork %d and %d down\n",
philosopher_number + 1, LEFT + 1, philosopher_number + 1);
printf("Philosopher %d is Thinking\n", philosopher_number + 1);
// Check if left and right neighbors can eat now
test(LEFT);
test(RIGHT);
sem_post(&mutex); // Exit critical section
}
// Function for philosopher behavior
void* philosopher(void* num) {
while (1) {
int* i = num;
sleep(1); // Philosopher is thinking
take_fork(*i);
sleep(0); // Philosopher is eating
put_fork(*i);
}
}
int main() {
pthread_t thread_id[N]; // Thread IDs for philosophers
// Initialize the semaphores
sem_init(&mutex, 0, 1);
for (int i = 0; i < N; i++)
sem_init(&S[i], 0, 0);
// Create philosopher processes
for (int i = 0; i < N; i++) {
pthread_create(&thread_id[i], NULL, philosopher, &philosophers[i]);
printf("Philosopher %d is thinking\n", i + 1);
}
// Join philosopher threads
for (int i = 0; i < N; i++)
pthread_join(thread_id[i], NULL);
return 0;
}
Output:
Philosopher 1 is thinking
Philosopher 2 is thinking
Philosopher 3 is thinking
Philosopher 4 is thinking
Philosopher 5 is thinking
Philosopher 1 is Hungry
Philosopher 1 takes fork 5 and 1
Philosopher 1 is Eating
Philosopher 3 is Hungry
Philosopher 3 takes fork 2 and 3
Philosopher 3 is Eating
Philosopher 1 putting fork 5 and 1 down
Philosopher 1 is Thinking
Philosopher 4 is Hungry
Philosopher 4 takes fork 3 and 4
Philosopher 4 is Eating
...
Producer-consumer :
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define BUFFER_SIZE 5 // Define the size of the buffer
int buffer[BUFFER_SIZE]; // Buffer for storing items
int in = 0, out = 0; // Index variables for the buffer
int count = 0; // Counter for the number of items in the buffer
sem_t empty; // Semaphore to keep track of empty slots in the buffer
sem_t full; // Semaphore to keep track of filled slots in the buffer
pthread_mutex_t mutex; // Mutex lock for critical section
// Function for the producer to produce items
void* producer(void* arg) {
int item;
while (1) {
item = rand() % 100; // Produce a random item
sem_wait(&empty); // Wait if buffer is full
pthread_mutex_lock(&mutex); // Enter critical section
// Add the produced item to the buffer
buffer[in] = item;
in = (in + 1) % BUFFER_SIZE; // Increment buffer index
count++;
printf("Producer produced: %d\n", item);
pthread_mutex_unlock(&mutex); // Exit critical section
sem_post(&full); // Signal that buffer has one more filled slot
sleep(1); // Sleep for a while before producing next item
}
}
// Function for the consumer to consume items
void* consumer(void* arg) {
int item;
while (1) {
sem_wait(&full); // Wait if buffer is empty
pthread_mutex_lock(&mutex); // Enter critical section
// Remove an item from the buffer
item = buffer[out];
out = (out + 1) % BUFFER_SIZE; // Increment buffer index
count--;
printf("Consumer consumed: %d\n", item);
pthread_mutex_unlock(&mutex); // Exit critical section
sem_post(&empty); // Signal that buffer has one more empty slot
sleep(1); // Sleep for a while before consuming next item
}
}
int main() {
pthread_t prod, cons;
// Initialize the semaphores and mutex
sem_init(&empty, 0, BUFFER_SIZE); // Initially, buffer has BUFFER_SIZE empty slots
sem_init(&full, 0, 0); // Initially, buffer has 0 filled slots
pthread_mutex_init(&mutex, NULL);
// Create producer and consumer threads
pthread_create(&prod, NULL, producer, NULL);
pthread_create(&cons, NULL, consumer, NULL);
// Join threads
pthread_join(prod, NULL);
pthread_join(cons, NULL);
// Destroy the semaphores and mutex
sem_destroy(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);
return 0;
}
Output:
Producer produced: 15
Consumer consumed: 15
Producer produced: 28
Consumer consumed: 28
Producer produced: 42
Consumer consumed: 42
Producer produced: 99
Consumer consumed: 99
Producer produced: 37
Consumer consumed: 37
Producer produced: 74
Consumer consumed: 74
Experiment-9
DEAD LOCK AVOIDANCE:
AIM: To Simulate bankers algorithm for Dead Lock Avoidance (Banker‘s Algorithm)
1. 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
userrequest 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.
ALGORITHM:
1. Start the program.
2. 2. Get the values of resources and processes.
3. Get the avail value.
4. After allocation find the need value.
5. Check whether its possible to allocate.
6. If it is possible then the system is in safe state.
7. Else system is not in safety state.
8. If the new request comes then check that the system is in safety.
9. or not if we allow the request.
10. stop the program.
11. End
SOURCE CODE :
#include <stdio.h>
#include <stdbool.h>
void calculateNeed(int need[10][10], int max[10][10], int allocation[10][10], int n, int
m) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
need[i][j] = max[i][j] - allocation[i][j];
bool isSafe(int processes[], int avail[], int max[][10], int allocation[][10], int n, int m) {
int need[10][10];
calculateNeed(need, max, allocation, n, m);
bool finish[10] = {0}; // Array to keep track of processes that are completed
int safeSeq[10]; // Array to store safe sequence
int work[10]; // Temporary array to store available resources
for (int i = 0; i < m; i++) {
work[i] = avail[i]; // Initialize work with available resources
int count = 0; // Count of processes that are included in the safe sequence
while (count < n) {
bool found = false;
for (int p = 0; p < n; p++) {
if (!finish[p]) { // If process p is not finished
int j;
for (j = 0; j < m; j++) {
if (need[p][j] > work[j]) {
break;
// If all resources needed by p are available
if (j == m) {
for (int k = 0; k < m; k++) {
work[k] += allocation[p][k];
safeSeq[count++] = p;
finish[p] = 1;
found = true;
// If no process was able to be allocated resources, return false
if (!found) {
printf("System is not in a safe state.\n");
return false;
// If the system is in a safe state, print the safe sequence
printf("System is in a safe state.\nSafe sequence is: ");
for (int i = 0; i < n; i++) {
printf("%d ", safeSeq[i]);
}
printf("\n");
return true;
int main() {
int n, m;
printf("Enter the number of processes: ");
scanf("%d", &n);
printf("Enter the number of resource types: ");
scanf("%d", &m);
int processes[n], avail[m], max[10][10], allocation[10][10];
printf("Enter the available resources for each type: ");
for (int i = 0; i < m; i++) {
scanf("%d", &avail[i]);
printf("Enter the maximum resource matrix:\n");
for (int i = 0; i < n; i++) {
printf("For process %d: ", i);
for (int j = 0; j < m; j++) {
scanf("%d", &max[i][j]);
}
printf("Enter the allocation matrix:\n");
for (int i = 0; i < n; i++) {
printf("For process %d: ", i);
for (int j = 0; j < m; j++) {
scanf("%d", &allocation[i][j]);
// Check if the system is in a safe state
isSafe(processes, avail, max, allocation, n, m);
return 0;
input:
Enter the number of processes: 5
Enter the number of resource types: 3
Enter the available resources for each type: 3 3 2
Enter the maximum resource matrix:
For process 0: 7 5 3
For process 1: 3 2 2
For process 2: 9 0 2
For process 3: 2 2 2
For process 4: 4 3 3
Enter the allocation matrix:
For process 0: 0 1 0
For process 1: 2 0 0
For process 2: 3 0 2
For process 3: 2 1 1
For process 4: 0 0 2
Output:
System is in a safe state.
Safe sequence is: 1 3 4 0 2
Experiment-10
Dead lock prevention:
AIM: To implement deadlock prevention technique
Banker‘s Algorithm: 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
Program:
#include <stdio.h>
#include <stdbool.h>
#define NUM_PROCESSES 5 // Number of processes
#define NUM_RESOURCES 3 // Number of resource types
void printState(int allocation[NUM_PROCESSES][NUM_RESOURCES], int
request[NUM_PROCESSES][NUM_RESOURCES], int avail[NUM_RESOURCES])
{
printf("Current State of Allocation Matrix:\n");
for (int i = 0; i < NUM_PROCESSES; i++) {
for (int j = 0; j < NUM_RESOURCES; j++) {
printf("%d ", allocation[i][j]);
printf("\n");
}
printf("\nCurrent State of Request Matrix:\n");
for (int i = 0; i < NUM_PROCESSES; i++) {
for (int j = 0; j < NUM_RESOURCES; j++) {
printf("%d ", request[i][j]);
printf("\n");
printf("\nAvailable Resources:\n");
for (int i = 0; i < NUM_RESOURCES; i++) {
printf("%d ", avail[i]);
printf("\n\n");
bool canAllocate(int process, int request[NUM_PROCESSES][NUM_RESOURCES],
int avail[NUM_RESOURCES]) {
for (int j = 0; j < NUM_RESOURCES; j++) {
if (request[process][j] > avail[j]) {
return false; // Cannot allocate if the request is greater than available resources
return true;
}
void resourceAllocation(int allocation[NUM_PROCESSES][NUM_RESOURCES], int
request[NUM_PROCESSES][NUM_RESOURCES], int avail[NUM_RESOURCES])
{
for (int i = 0; i < NUM_PROCESSES; i++) {
if (canAllocate(i, request, avail)) {
printf("Process %d's request can be granted.\n", i);
// Allocate resources
for (int j = 0; j < NUM_RESOURCES; j++) {
avail[j] -= request[i][j]; // Reduce available resources
allocation[i][j] += request[i][j]; // Allocate to process
request[i][j] = 0; // Reset request after allocation
} else {
printf("Process %d's request cannot be granted due to lack of resources.\n", i);
int main() {
int allocation[NUM_PROCESSES][NUM_RESOURCES] = {
{0, 1, 0}, // Allocation for Process 0
{2, 0, 0}, // Allocation for Process 1
{3, 0, 2}, // Allocation for Process 2
{2, 1, 1}, // Allocation for Process 3
{0, 0, 2} // Allocation for Process 4
};
int request[NUM_PROCESSES][NUM_RESOURCES] = {
{0, 0, 0}, // Request for Process 0
{0, 0, 0}, // Request for Process 1
{0, 0, 0}, // Request for Process 2
{0, 0, 0}, // Request for Process 3
{0, 0, 0} // Request for Process 4
};
int avail[NUM_RESOURCES] = {3, 3, 2}; // Available resources
printf("Deadlock Prevention using Resource Allocation and Ordering\n");
printState(allocation, request, avail);
// Simulate resource requests for processes
printf("Simulating resource requests...\n");
request[0][0] = 0; request[0][1] = 2; request[0][2] = 0;
request[1][0] = 2; request[1][1] = 0; request[1][2] = 2;
request[3][0] = 0; request[3][1] = 0; request[3][2] = 2;
printState(allocation, request, avail);
resourceAllocation(allocation, request, avail);
printf("After allocation, state is:\n");
printState(allocation, request, avail);
return 0;
Output:
Deadlock Prevention using Resource Allocation and Ordering
Current State of Allocation Matrix:
010
200
302
211
002
Current State of Request Matrix:
000
000
000
000
000
Available Resources:
332
Simulating resource requests...
Current State of Allocation Matrix:
010
200
302
211
002
Current State of Request Matrix:
020
202
000
002
000
Available Resources:
332
Process 0's request can be granted.
Process 1's request can be granted.
Process 3's request cannot be granted due to lack of resources.
After allocation, state is:
Current State of Allocation Matrix:
030
402
302
211
002
Current State of Request Matrix:
000
000
000
002
000
Available Resources:
100
Experiment - 11
Page replacement algorithms:
EXPERIMENT NO.6 PAGE REPLACEMENT ALGORITHMS AIM: To implement
FIFO page replacement technique. a) FIFO b) LRU c) OPTIMAL 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-In this
algorithm page will be replaced which is least recently used OPTIMAL- In this
algorithm, pages are replaced which would not be used for the longest duration of time
in the future. This algorithm will give us less page fault when compared to other page
replacement algorithms.
ALGORITHM:
1. Start the process
2. Read number of pages n
3. Read number of pages no
4. Read page numbers into an array a[i]
5. Initialize avail[i]=0 .to check page hit
6. Replace the page with circular queue, while re-placing check page availability in the
frame Place avail[i]=1 if page is placed in theframe Count page faults
7. Print the results.
8. Stop the process.
A) FIFO
#include <stdio.h>
void printFrames(int frames[], int num_frames) {
printf("Current Frames: ");
for (int i = 0; i < num_frames; i++) {
if (frames[i] == -1)
printf(" [ ]");
else
printf(" [%d]", frames[i]);
printf("\n");
int main() {
int num_pages, num_frames;
printf("Enter the number of pages: ");
scanf("%d", &num_pages);
printf("Enter the number of frames: ");
scanf("%d", &num_frames);
int pages[num_pages];
int frames[num_frames];
int page_faults = 0;
// Initialize frame array with -1 to indicate empty slots
for (int i = 0; i < num_frames; i++) {
frames[i] = -1;
printf("Enter the page reference string:\n");
for (int i = 0; i < num_pages; i++) {
printf("Page %d: ", i + 1);
scanf("%d", &pages[i]);
int index = 0; // Points to the frame that should be replaced next
for (int i = 0; i < num_pages; i++) {
int page = pages[i];
int flag = 0; // Flag to check if page is already in frame
// Check if page is already in one of the frames
for (int j = 0; j < num_frames; j++) {
if (frames[j] == page) {
flag = 1; // Page is already in a frame, no page fault
break;
// If page is not found in frames, replace using FIFO strategy
if (!flag) {
frames[index] = page; // Replace the oldest frame with the current page
index = (index + 1) % num_frames; // Move to the next frame index in a circular
manner
page_faults++;
printf("Page %d caused a page fault.\n", page);
} else {
printf("Page %d did not cause a page fault.\n", page);
printFrames(frames, num_frames); // Print the current state of frames
printf("\nTotal number of page faults: %d\n", page_faults);
return 0;
Input:
Enter the number of pages: 9
Enter the number of frames: 3
Enter the page reference string:
Page 1: 1
Page 2: 3
Page 3: 0
Page 4: 3
Page 5: 5
Page 6: 6
Page 7: 3
Page 8: 5
Page 9: 6
Output:
Page 1 caused a page fault.
Current Frames: [1] [ ] [ ]
Page 3 caused a page fault.
Current Frames: [1] [3] [ ]
Page 0 caused a page fault.
Current Frames: [1] [3] [0]
Page 3 did not cause a page fault.
Current Frames: [1] [3] [0]
Page 5 caused a page fault.
Current Frames: [5] [3] [0]
Page 6 caused a page fault.
Current Frames: [5] [6] [0]
Page 3 caused a page fault.
Current Frames: [5] [6] [3]
Page 5 caused a page fault.
Current Frames: [5] [6] [3]
Page 6 did not cause a page fault.
Current Frames: [5] [6] [3]
Total number of page faults: 6
B) LRU:
#include <stdio.h>
void printFrames(int frames[], int num_frames) {
printf("Current Frames: ");
for (int i = 0; i < num_frames; i++) {
if (frames[i] == -1)
printf(" [ ]");
else
printf(" [%d]", frames[i]);
printf("\n");
// Function to find the index of the least recently used page
int findLRU(int last_used[], int num_frames) {
int lru_index = 0;
for (int i = 1; i < num_frames; i++) {
if (last_used[i] < last_used[lru_index]) {
lru_index = i;
return lru_index;
int main() {
int num_pages, num_frames;
printf("Enter the number of pages: ");
scanf("%d", &num_pages);
printf("Enter the number of frames: ");
scanf("%d", &num_frames);
int pages[num_pages];
int frames[num_frames];
int last_used[num_frames];
int page_faults = 0;
// Initialize frame and last_used arrays
for (int i = 0; i < num_frames; i++) {
frames[i] = -1;
last_used[i] = -1;
printf("Enter the page reference string:\n");
for (int i = 0; i < num_pages; i++) {
printf("Page %d: ", i + 1);
scanf("%d", &pages[i]);
for (int i = 0; i < num_pages; i++) {
int page = pages[i];
int found = 0;
// Check if page is already in one of the frames
for (int j = 0; j < num_frames; j++) {
if (frames[j] == page) {
found = 1; // Page is found
last_used[j] = i; // Update last used time
break;
// If page is not found, we have a page fault
if (!found) {
int lru_index = findLRU(last_used, num_frames); // Get the index of LRU page
frames[lru_index] = page; // Replace LRU page with the current page
last_used[lru_index] = i; // Update last used time
page_faults++;
printf("Page %d caused a page fault.\n", page);
} else {
printf("Page %d did not cause a page fault.\n", page);
printFrames(frames, num_frames); // Print the current state of frames
printf("\nTotal number of page faults: %d\n", page_faults);
return 0;
Input & output:
Enter the number of pages: 9
Enter the number of frames: 3
Enter the page reference string:
Page 1: 7
Page 2: 0
Page 3: 1
Page 4: 2
Page 5: 0
Page 6: 3
Page 7: 0
Page 8: 4
Page 9: 2
Page 7 caused a page fault.
Current Frames: [7] [ ] [ ]
Page 0 caused a page fault.
Current Frames: [7] [0] [ ]
Page 1 caused a page fault.
Current Frames: [7] [0] [1]
Page 2 caused a page fault.
Current Frames: [2] [0] [1]
Page 0 did not cause a page fault.
Current Frames: [2] [0] [1]
Page 3 caused a page fault.
Current Frames: [2] [3] [1]
Page 0 caused a page fault.
Current Frames: [0] [3] [1]
Page 4 caused a page fault.
Current Frames: [0] [3] [4]
Page 2 caused a page fault.
Current Frames: [2] [3] [4]
Total number of page faults: 6
C) OPTIMAL
#include <stdio.h>
#include <limits.h>
void printFrames(int frames[], int num_frames) {
printf("Current Frames: ");
for (int i = 0; i < num_frames; i++) {
if (frames[i] == -1)
printf(" [ ]");
else
printf(" [%d]", frames[i]);
printf("\n");
// Function to find the optimal page to replace
int findOptimal(int frames[], int num_frames, int pages[], int current_index, int
num_pages) {
int furthest_index = -1;
int page_to_replace = -1;
for (int i = 0; i < num_frames; i++) {
int j;
for (j = current_index; j < num_pages; j++) {
if (frames[i] == pages[j]) {
if (j > furthest_index) {
furthest_index = j;
page_to_replace = i; // Replace this page
break;
// If the page is not found, it can be replaced
if (j == num_pages) {
return i; // Return index to replace this page
// If all pages are found, replace the one that will be used furthest in the future
return page_to_replace;
int main() {
int num_pages, num_frames;
printf("Enter the number of pages: ");
scanf("%d", &num_pages);
printf("Enter the number of frames: ");
scanf("%d", &num_frames);
int pages[num_pages];
int frames[num_frames];
int page_faults = 0;
// Initialize frames array
for (int i = 0; i < num_frames; i++) {
frames[i] = -1;
printf("Enter the page reference string:\n");
for (int i = 0; i < num_pages; i++) {
printf("Page %d: ", i + 1);
scanf("%d", &pages[i]);
for (int i = 0; i < num_pages; i++) {
int page = pages[i];
int found = 0;
// Check if page is already in one of the frames
for (int j = 0; j < num_frames; j++) {
if (frames[j] == page) {
found = 1; // Page is found
break;
// If page is not found, we have a page fault
if (!found) {
int replace_index = findOptimal(frames, num_frames, pages, i + 1,
num_pages);
frames[replace_index] = page; // Replace the chosen page with the current
page
page_faults++;
printf("Page %d caused a page fault.\n", page);
} else {
printf("Page %d did not cause a page fault.\n", page);
printFrames(frames, num_frames); // Print the current state of frames
printf("\nTotal number of page faults: %d\n", page_faults);
return 0;
Input & output:
Enter the number of pages: 9
Enter the number of frames: 3
Enter the page reference string:
Page 1: 7
Page 2: 0
Page 3: 1
Page 4: 2
Page 5: 0
Page 6: 3
Page 7: 0
Page 8: 4
Page 9: 2
Page 7 caused a page fault.
Current Frames: [7] [ ] [ ]
Page 0 caused a page fault.
Current Frames: [7] [0] [ ]
Page 1 caused a page fault.
Current Frames: [7] [0] [1]
Page 2 caused a page fault.
Current Frames: [2] [0] [1]
Page 0 did not cause a page fault.
Current Frames: [2] [0] [1]
Page 3 caused a page fault.
Current Frames: [2] [0] [3]
Page 0 did not cause a page fault.
Current Frames: [2] [0] [3]
Page 4 caused a page fault.
Current Frames: [4] [0] [3]
Page 2 did not cause a page fault.
Current Frames: [4] [0] [3]
Total number of page faults: 6