2021UCA1930 (Ospractical)

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 84

Operating System Practical File

-Shreyansh Agarwal
-2021UCA1930
-------------------------------------
Question 1: Write a program for system calls, fork(),
wait(), exit(), signal(), getpid(), getppid()
//getpid() Call:
// C++ Code to demonstrate getpid()
#include <iostream>
#include <unistd.h>
using namespace std;

// Driver Code
int main()
{
int pid = fork();
if (pid == 0)
cout << "\nCurrent process id of Process : "
<< getpid() << endl;
return 0;
}

Output:

//getppid() Call:
// C++ Code to demonstrate getppid()
#include <iostream>
#include <unistd.h>
using namespace std;

// Driver Code
int main()
{
int pid;
pid = fork();
if (pid == 0)
{
cout << "\nParent Process id : "
<< getpid() << endl;
cout << "\nChild Process with parent id : "
<< getppid() << endl;
}
return 0;
}

Output:

//Fork() Call:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
pid_t p;
printf("before fork\n");
p = fork();
if (p == 0) {
printf("I am child having id %d\n", getpid());
printf("My parent's id is %d\n", getppid());
}
else {
printf("My child's id is %d\n", p);
printf("I am parent having id %d\n", getpid());
}
printf("Common\n");
}

Output:

//Wait () Call:

#include<unistd.h>
#include<sys/types.h>
#include<stdio.h>
#include<sys/wait.h>
int main()
{
pid_t p;
printf("before fork\n");
p = fork();
if (p == 0) //child
{
printf("I am child having id %d\n", getpid());
printf("My parent's id is %d\n", getppid());
}
else//parent
{
wait(NULL);
printf("My child's id is %d\n", p);
printf("I am parent having id %d\n", getpid());
}
printf("Common\n");

Output:

//Signal () Call:

#include<stdio.h>
#include<signal.h>

void handle_sigint(int sig)


{
printf("Caught signal %d\n", sig);
}

int main()
{
signal(SIGINT, handle_sigint);
while (1) ;
return 0;
}

Output:

//Exit () Call:
#include <stdio.h>
#include <stdlib.h>

int main ()
{
FILE * pFile;
pFile = fopen ("myfile.txt", "r");
if (pFile == NULL)
{
printf ("Error opening file");
exit (1);
}
else
{
/* file operations here */
}
return 0;
}

Output:

Question 2: (i)Bounded Buffer Problem (Producer-


Consumer)
//Bounded-Buffer

#include <stdio.h>
#include <stdlib.h>
int mutex = 1, full = 0, empty = 3, x = 0;
int main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf("\n1.Producer\n2.Consumer\n3.Exit");
while (1)
{
printf("\nEnter your choice:");
scanf("%d", &n);
switch (n)
{
case 1:
if ((mutex == 1) && (empty != 0))
producer();
else
printf("Buffer is full!!");
break;
case 2:
if ((mutex == 1) && (full != 0))
consumer();
else
printf("Buffer is empty!!");
break;
case 3:
exit(0);
break;
}
}
return 0;
}
int wait(int s)
{
return (--s);
}
int signal(int s)
{
return (++s);
}
void producer()
{
mutex = wait(mutex);
full = signal(full);
empty = wait(empty);
x++;
printf("\nProducer produces the item %d", x);
mutex = signal(mutex);
}
void consumer()
{
mutex = wait(mutex);
full = wait(full);
empty = signal(empty);
printf("\nConsumer consumes item %d", x);
x--;
mutex = signal(mutex);
}

//Unbounded Buffer
#include <stdio.h>
#include <stdlib.h>
#include <climits>
int mutex = 1, full = 0, empty = INT_MAX, x = 0;
int main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf("\n1.Producer\n2.Consumer\n3.Exit");
while (1)
{
printf("\nEnter your choice:");
scanf("%d", &n);
switch (n)
{
case 1:
if ((mutex == 1) && (empty != 0))
producer();
else
printf("Buffer is full!!");
break;
case 2:
if ((mutex == 1) && (full != 0))
consumer();
else
printf("Buffer is empty!!");
break;
case 3:
exit(0);
break;
}
}
return 0;
}
int wait(int s)
{
return (--s);
}
int signal(int s)
{
return (++s);
}
void producer()
{
mutex = wait(mutex);
full = signal(full);
empty = wait(empty);
x++;
printf("\nProducer produces the item %d", x);
mutex = signal(mutex);
}
void consumer()
{
mutex = wait(mutex);
full = wait(full);
empty = signal(empty);
printf("\nConsumer consumes item %d", x);
x--;
mutex = signal(mutex);
}

Output:
Bounded Buffer:

Unbounded Buffer:

Question 2: (ii)IPC (Producer-Consumer)


//Writer.cpp:
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
using namespace std;
int main() {
//ftok function is used to generate unique key
key_t my_key = ftok("shmfile",65);
//shmat to join to shared memory
int shmid = shmget(my_key,1024,0666|IPC_CREAT);
char *str = (char*) shmat(shmid,(void*)0,0);
cout<<"Write Data : ";
fgets(str, 50, stdin);
printf("Data written in memory: %s\n",str);
//detach from shared memory
shmdt(str);
}

//Reader.cpp:
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
using namespace std;
int main()
{
//ftok function is used to generate unique key
key_t my_key = ftok("shmfile",65);
//shmget returns an ide in shmid
int shmid = shmget(my_key,1024,0666|IPC_CREAT);
//shmat to join to shared memory
char *str = (char*) shmat(shmid,(void*)0,0);
printf("Data read from memory: %s\n",str);
shmdt(str);
shmctl(shmid,IPC_RMID,NULL); // destroy the shared memory
}

Question 3: Implement CPU scheduling algorithms:


FCFS, SJF, Round Robin, Preemptive Priority
Scheduling.
//FCFS Algo
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout << "Enter the no of processes\n";
cin >> n;
vector<pair<string, int> >v;
cout << "Enter the process name and its burst time\n";
while (n--)
{
string str;
cin >> str;
int val;
cin >> val;
v.push_back(make_pair(str, val));
}
cout << "Order of execution and waiting time for each
process is\n";
int sum = 0;
float average = 0;
int x = 150;
for (int i = 0; i < v.size(); i++)
{
cout << v[i].first << " " << sum << endl;
average += sum;
sum += v[i].second;
}
sum = 0;
for (int i = 0; i < v.size(); i++)
{
char intAsString [10];
x = x + 10 * v[i].second;
sum += v[i].second;
}
cout << endl << "Average waiting time is " << average /
v.size();
cout << endl;
return 0;
}

//SJF Algo
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define f(i, n) for (int i = 0; i < n; i++)
void DDA(float x1, float y1, float x2, float y2, int i, int
buffer = 0)
{
float dx = x2 - x1;
float dy = y2 - y1;
// Finding slope
float m = dy / dx;
float steps;
if (abs(m) <= 1)
{

steps = abs(dx);
}
else
{
steps = abs(dy);
}
float Delx = dx / steps;
float Dely = dy / steps;
float x = x1, y = y1;
for (int k = 1; k <= steps; k++)
{
x = x + Delx;
y = y + Dely;
}
}
void makeRect( int x, int y, int i, int t) //t is thickness
i,e, time
{
{
DDA(x, y, t * 10 + x, y, i);
DDA(x + t * 10, y, t * 10 + x, y + 50, i);
DDA(x + t * 10, y + 50, x, 50 + y, i);
DDA(x, y + 50, x, y, i);
}
}
void intToString(int num, char str[100]) {
if (num == 0) {
str[0] = '0';
str[1] = '\0';
return;
}
int num_of_digits = 0, temp = num;
while (temp) {
++num_of_digits;
temp /= 10;
}
str[num_of_digits] = '\0';
temp = num;
int i = num_of_digits - 1;
while (temp) {
str[i] = '0' + (temp % 10);
temp /= 10;
--i;
}
}
int main()
{
cout << "enter number of processes\n";
int n;
cin >> n;
int burstTimes[n];
cout << "Enter the burst times \n";
f(i, n) {
cout << "Process " << (i + 1) << "th :";
cin >> burstTimes[i];
}
sort(burstTimes, burstTimes + n);
int x = 100, y = 100;
f(i, n) {
makeRect(x, y, (i % 8) + 1, burstTimes[i]);
char c[3];
c[0] = 'P';
c[1] = '1' + i;
x += burstTimes[i] * 10;
}
int waitingTimes[n];
int turnaround = 0;
float avgWait = 0;
x = 100;
f(i, n) {
cout << "For process " << (i + 1) << "\n";
// cout<<"Turnaround time = ";
turnaround += burstTimes[i];
// cout<<turnaround<<endl;
cout << "waiting time : ";
waitingTimes[i] = (turnaround - burstTimes[i]);
cout << waitingTimes[i];
avgWait += waitingTimes[i];
cout << endl << endl;
//gantt chart
makeRect(x, y, (i % 8) + 3, burstTimes[i]);
char c[100];
intToString(waitingTimes[i], c);
x += burstTimes[i] * 10;
}
avgWait = avgWait / n;
cout << "Avg wait time: " << avgWait << endl;
return 0;

//Round Robin Algo


#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout << "Enter the number of processes\n";
cin >> n;
int a[n];
int temp[n];
cout << "Enter the burst time of the processes\n";
for (int i = 0; i < n; i++)
{
cin >> a[i];
temp[i] = a[i];
}
int quantum;
cout << "Enter the quantum time\n";
cin >> quantum;
int wt[n];
int t = 0;
while (1)
{
bool comp = true;
for (int i = 0 ; i < n; i++)
{

if (temp[i] > 0)
{
comp = false;
if (temp[i] > quantum)
{
t += quantum;
temp[i] -= quantum;
}
else
{
t = t + temp[i];
wt[i] = t - a[i];
temp[i] = 0;
}
}
}
if (comp)
{
break;
}
}
float turn = 0;
cout << "Waiting times are\n";
float wait = 0;
for (int i = 0; i < n; i++)
{
cout << wt[i] << " ";
wait += float(wt[i]);
turn += (float(wt[i]) + float(a[i]));
}
cout << endl;
cout << "Turnaround times are\n";
for (int i = 0; i < n; i++)
{
cout << wt[i] + a[i] << " ";
}
cout << endl;
cout << "Average waiting time is " << wait / n << " s" <<
endl;
cout << "Average turnaround time is " << turn / n << " s"
<< endl;
return 0;
}

//Preemptive Priority Scheduling Algo


#include<iostream>
using namespace std;
#include<cmath>
#include<string>
#include<algorithm>
using namespace std;
void drawLineDDA(float x1, float y1, float x2, float y2, int
i, int buffer = 0)
{
float dx = x2 - x1;
float dy = y2 - y1;
// Finding slope
float m = dy / dx;
float steps;
if (abs(m) <= 1)
{
steps = abs(dx);
}
else
{
steps = abs(dy);
}
float Delx = dx / steps;
float Dely = dy / steps;
float x = x1, y = y1;
for (int k = 1; k <= steps; k++)
{
x = x + Delx;
y = y + Dely;
}
}
void drawRectangle( int x, int y, int i, int t) //t is
thickness i,e, time
{
{
drawLineDDA(x, y, t * 10 + x, y, i);
drawLineDDA(x + t * 10, y, t * 10 + x, y + 50, i);
drawLineDDA(x + t * 10, y + 50, x, 50 + y, i);
drawLineDDA(x, y + 50, x, y, i);
}
}
void int_to_string(int num, char str[100]) {
if (num == 0) {
str[0] = '0';
str[1] = '\0';
return;
}
int num_of_digits = 0, temp = num;
while (temp) {
++num_of_digits;
temp /= 10;
}
str[num_of_digits] = '\0';
temp = num;
int i = num_of_digits - 1;
while (temp) {
str[i] = '0' + (temp % 10);
temp /= 10;
--i;
}
}
class Process
{
public:
int burst_Time;
int process_num;
int arrival_time = 0;
int org_arrival_time;
int org_burst_time;
int priority;
};
bool ValueCmp1(Process const & a, Process const & b)
{
if (a.arrival_time < b.arrival_time)
return 1;
else if (a.arrival_time > b.arrival_time)
return 0;
else
return a.priority < b.priority;
}
bool ValueCmp(Process const & a, Process const & b)
{
return a.priority < b.priority;
}
int main()
{
cout << "\n Input the number of processes :\t";
int num_task;
cin >> num_task;
cout << "\n Enter 1 for non-preemptive and 2 for preemptive
scheduling\n";
int choice;
cin >> choice;
if (choice == 1)
{
Process tasks[num_task];
cout << "\n Enter the CPU bursts of the processes and
their priority:\t";
int x = 100, y = 100;
for (int i = 0; i < num_task; i++ )
{
cout << "\n Enter the CPU burst of process and it's
priority " << i + 1 << " :\t";
cin >> tasks[i].burst_Time;
cin >> tasks[i].priority;
tasks[i].process_num = i + 1;
}
sort(tasks, tasks + num_task, ValueCmp);
for (int i = 0; i < num_task; i++ )
{
drawRectangle(x, y, (i % 8) + 1, tasks[i].burst_Time);
char str[3];
str[0] = 'P';
str[1] = '0' + tasks[i].process_num;
x += tasks[i].burst_Time * 10;
}
int waiting_time = 0;
int sum_waiting_time = 0;
// int turnaround_time=0;
// int sum_turnaround_time=0;
x = 100;
for (int i = 0; i < num_task; i++)
{
sum_waiting_time += waiting_time;
//turnaround_time=waiting_time+tasks[i];
//sum_turnaround_time+=turnaround_time;
cout << "\n Waiting time for " << tasks[i].process_num
<< " task is:\t" << waiting_time << " secs";
// cout<<"\n Turnaround time for "<<i+1<<" task is:\
t"<<turnaround_time<<" secs \n";
drawRectangle(x, y, (i % 8) + 3, tasks[i].burst_Time);
char str[100];
int_to_string(waiting_time, str);
x += (tasks[i].burst_Time) * 10;
waiting_time += tasks[i].burst_Time;
}
cout << "\n\n Average waiting time : \t" <<
float(sum_waiting_time) / num_task << " secs.";
}
else {
Process tasks[num_task];
cout << "\n Enter the CPU bursts of the processes:\t";
int waiting_time = 0;
int x = 100, y = 100;
for (int i = 0; i < num_task; i++ )
{
cout << "\n Enter the CPU burst of process and arrival
time and priority " << i + 1 << " :\t";
cin >> tasks[i].burst_Time;
cin >> tasks[i].arrival_time;
cin >> tasks[i].priority;
tasks[i].process_num = i + 1;
tasks[i].org_arrival_time = tasks[i].arrival_time;
tasks[i].org_burst_time = tasks[i].burst_Time;
}
sort(tasks, tasks + num_task, ValueCmp1);
char arr[100];
int_to_string(tasks[0].arrival_time, arr);
for (int i = 0; 1; i++ )
{
if (tasks[0].burst_Time >= 190000)
break;
drawRectangle(x, y, tasks[0].process_num, 5);
char str[3];
str[0] = 'P';
str[1] = '0' + tasks[0].process_num;
str[2] = '\0';
x += 50;
tasks[0].burst_Time -= 1;
tasks[0].arrival_time += 1;
for (int j = 0; j < num_task; j++)
if (tasks[j].arrival_time < tasks[0].arrival_time)
tasks[j].arrival_time = tasks[0].arrival_time;
char arr[100];
int_to_string(tasks[0].arrival_time, arr);
if (tasks[0].burst_Time == 0)
{
tasks[0].burst_Time = 190000; //INT_MAX ki jagh
char arr[2];
arr[0] = i + '0' + 1;
arr[1] = '\0';
// cout<<tasks[0].arrival_time<<"
"<<tasks[0].org_arrival_time<<"
"<<tasks[0].org_burst_time<<endl;
cout << "Waiting time for process " <<
tasks[0].process_num << " is:\t" << (tasks[0].arrival_time -
tasks[0].org_arrival_time) - tasks[0].org_burst_time <<
"secs" << endl;
waiting_time += (tasks[0].arrival_time -
tasks[0].org_arrival_time) - tasks[0].org_burst_time;
tasks[0].arrival_time = 190000;
tasks[0].priority = 1900000;
}
sort(tasks, tasks + num_task, ValueCmp1);
}
cout << "\n Average waiting time :\t" <<
float(waiting_time) / num_task << " secs";
cout << endl;
}
return 0;
}

//MultiLevel FeedBack Queue:


#include<stdio.h>

struct process
{
char name;
int AT,BT,WT,TAT,RT,CT;
}Q1[10],Q2[10],Q3[10];/*Three queues*/

int n;
void sortByArrival()
{
struct process temp;
int i,j;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(Q1[i].AT>Q1[j].AT)
{
temp=Q1[i];
Q1[i]=Q1[j];
Q1[j]=temp;
}
}
}
}

int main()
{
int i,j,k=0,r=0,time=0,tq1=5,tq2=8,flag=0;
char c;
printf("Enter no of processes:");
scanf("%d",&n);
for(i=0,c='A';i<n;i++,c++)
{
Q1[i].name=c;
printf("\nEnter the arrival time and burst time of
process %c: ",Q1[i].name);
scanf("%d%d",&Q1[i].AT,&Q1[i].BT);
Q1[i].RT=Q1[i].BT;/*save burst time in remaining
time for each process*/

}
sortByArrival();
time=Q1[0].AT;
printf("Process in first queue following RR with qt=5");
printf("\nProcess\t\tRT\t\tWT\t\tTAT\t\t");
for(i=0;i<n;i++)
{

if(Q1[i].RT<=tq1)
{
time+=Q1[i].RT;/*from arrival time of first process to
completion of this process*/
Q1[i].RT=0;
Q1[i].WT=time-Q1[i].AT-Q1[i].BT;/*amount of time
process has been waiting in the first queue*/
Q1[i].TAT=time-Q1[i].AT;/*amount of time to execute
the process*/
printf("\n%c\t\t%d\t\t%d\t\t
%d",Q1[i].name,Q1[i].BT,Q1[i].WT,Q1[i].TAT);

}
else/*process moves to queue 2 with qt=8*/
{
Q2[k].WT=time;
time+=tq1;
Q1[i].RT-=tq1;
Q2[k].BT=Q1[i].RT;
Q2[k].RT=Q2[k].BT;
Q2[k].name=Q1[i].name;
k=k+1;
flag=1;
}
}
if(flag==1)
{printf("\nProcess in second queue following RR with qt=8");
printf("\nProcess\t\tRT\t\tWT\t\tTAT\t\t");
}for(i=0;i<k;i++)
{
if(Q2[i].RT<=tq2)
{
time+=Q2[i].RT;/*from arrival time of first process
+BT of this process*/
Q2[i].RT=0;
Q2[i].WT=time-tq1-Q2[i].BT;/*amount of time process
has been waiting in the ready queue*/
Q2[i].TAT=time-Q2[i].AT;/*amount of time to execute
the process*/
printf("\n%c\t\t%d\t\t%d\t\t
%d",Q2[i].name,Q2[i].BT,Q2[i].WT,Q2[i].TAT);
}
else/*process moves to queue 3 with FCFS*/
{
Q3[r].AT=time;
time+=tq2;
Q2[i].RT-=tq2;
Q3[r].BT=Q2[i].RT;
Q3[r].RT=Q3[r].BT;
Q3[r].name=Q2[i].name;
r=r+1;
flag=2;
}
}

{if(flag==2)
printf("\nProcess in third queue following FCFS ");
}
for(i=0;i<r;i++)
{
if(i==0)
Q3[i].CT=Q3[i].BT+time-tq1-tq2;
else
Q3[i].CT=Q3[i-1].CT+Q3[i].BT;

for(i=0;i<r;i++)
{
Q3[i].TAT=Q3[i].CT;
Q3[i].WT=Q3[i].TAT-Q3[i].BT;
printf("\n%c\t\t%d\t\t%d\t\t%d\t\
t",Q3[i].name,Q3[i].BT,Q3[i].WT,Q3[i].TAT);

}
Output:
FCFS:

SJF:

Round Robin:

Multilevel Feedback Queue:


Preemptive Priority Scheduling:

Question 4: Implement Critical Section Problem.


//Critical Section Problem
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#define MAX 1e9
int turn, ans = 0, flag[2];
void lock_init() {
flag[0] = flag[1] = 0;
turn = 0;
}
void lock(int self) {
flag[self] = 1;
turn = 1 - self;
while (flag[1 - self] ==1 && turn ==1 - self);
}
void unlock(int self) { flag[self] = 0; }
void *func(void *s)
{
int i = 0;
int *limitptr = (int *)s;
int self = *limitptr;
printf("Thread %d in queue for critical section\n", self);
lock(self);
printf("Thread %d entered critical section\n", self);
for (i = 0; i < MAX; i++)
ans ++;
printf("Thread %d completed executing\n", self);
printf("Thread %d is exiting critical section\n", self);
unlock(self);
}
int main() {
pthread_t p1, p2;
int a = 0, b = 1;
lock_init();
pthread_create(&p1, NULL, func, &a);
pthread_create(&p2, NULL, func, &b);
pthread_join(p1, NULL);
pthread_join(p2, NULL);
printf("Exiting main()\n");
return 0;
}

Output:
Question 5: Deadlock Detection and Deadlock
Avoidance Algorithm.

//Deadlock Avoidance (Banker’s Algorithm)


// C++ Program to Print all possible safe sequences using
banker's algorithm
#include <iostream>
#include <string.h>
#include <vector>
// total number of process
#define P 4
// total number of resources
#define R 3

// total safe-sequences
int total = 0;

using namespace std;

// function to check if process


// can be allocated or not
bool is_available(int process_id, int allocated[][R],
int max[][R], int need[][R], int
available[])
{

bool flag = true;

// check if all the available resources


// are less greater than need of process
for (int i = 0; i < R; i++) {

if (need[process_id][i] > available[i])


flag = false;
}

return flag;
}

// Print all the safe-sequences


void safe_sequence(bool marked[], int allocated[][R], int
max[][R],
int need[][R], int available[],
vector<int> safe)
{

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

// check if it is not marked


// already and can be allocated
if (!marked[i] && is_available(i, allocated, max,
need, available)) {

// mark the process


marked[i] = true;

// increase the available


// by deallocating from process i
for (int j = 0; j < R; j++)
available[j] += allocated[i][j];

safe.push_back(i);
// find safe sequence by taking process i
safe_sequence(marked, allocated, max, need,
available, safe);
safe.pop_back();

// unmark the process


marked[i] = false;

// decrease the available


for (int j = 0; j < R; j++)
available[j] -= allocated[i][j];
}
}
// if a safe-sequence is found, display it
if (safe.size() == P) {

total++;
for (int i = 0; i < P; i++) {

cout << "P" << safe[i] + 1;


if (i != (P - 1))
cout << "--> ";
}

cout << endl;


}
}

// Driver Code
int main()
{

// allocated matrix of size P*R


int allocated[P][R] = { { 0, 1, 0 },
{ 2, 0, 0 },
{ 3, 0, 2 },
{ 2, 1, 1 } };

// max matrix of size P*R


int max[P][R] = { { 7, 5, 3 },
{ 3, 2, 2 },
{ 9, 0, 2 },
{ 2, 2, 2 } };

// Initial total resources


int resources[R] = { 10, 5, 7 };

// available vector of size R


int available[R];

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


int sum = 0;
for (int j = 0; j < P; j++)
sum += allocated[j][i];

available[i] = resources[i] - sum;


}

// safe vector for displaying a safe-sequence


vector<int> safe;

// marked of size P for marking allocated process


bool marked[P];
memset(marked, false, sizeof(marked));

// need matrix of size P*R


int need[P][R];
for (int i = 0; i < P; i++)
for (int j = 0; j < R; j++)
need[i][j] = max[i][j] - allocated[i][j];

cout << "Safe sequences are:" << endl;


safe_sequence(marked, allocated, max, need, available,
safe);

cout << "\nThere are total " << total << " safe-
sequences" << endl;
return 0;
}

Output:
//Deadlock Detection
#include <bits/stdc++.h>
using namespace std;
int arrmax[100][100];
int alloc[100][100];
int need[100][100];
int avail[100];
int n, r;

void input()
{
int i, j;
cout << "Enter the no of Processes\t";
cin >> n;
cout << "Enter the no of resource instances\t";
cin >> r;
cout << "Enter the Max Matrix\n";
for (i = 0; i < n; i++)
{
for (j = 0; j < r; j++)
{
cin >> arrmax[i][j];
}
}
cout << "Enter the Allocation Matrix\n";
for (i = 0; i < n; i++)
{
for (j = 0; j < r; j++)
{
cin >> alloc[i][j];
}
}
cout << "Enter the available Resources\n";
for (j = 0; j < r; j++)
{
cin >> avail[j];
}
}
void show()
{
int i, j;
cout << "Process\t Allocation\t Max\t Available\t";
for (i = 0; i < n; i++)
{
cout << "\nP" << i + 1 << "\t ";
for (j = 0; j < r; j++)
{
cout << alloc[i][j] << " ";
}
cout << "\t\t";
for (j = 0; j < r; j++)
{
cout << arrmax[i][j] << " ";
}
cout << "\t ";
if (i == 0)
{
for (j = 0; j < r; j++)
cout << avail[j] << " ";
}
}
}
void cal()
{
int finish[100], temp, need[100][100], flag = 1, k, c1 =
0;
int dead[100];
int safe[100];
int i, j;
for (i = 0; i < n; i++)
{
finish[i] = 0;
}
//find need matrix
for (i = 0; i < n; i++)
{
for (j = 0; j < r; j++)
{
need[i][j] = arrmax[i][j] - alloc[i][j];
}
}
while (flag)
{
flag = 0;
for (i = 0; i < n; i++)
{
int c = 0;
for (j = 0; j < r; j++)
{
if ((finish[i] == 0) && (need[i][j] <=
avail[j]))
{
c++;
if (c == r)
{
for (k = 0; k < r; k++)
{
avail[k] += alloc[i][j];
finish[i] = 1;
flag = 1;
}
//cout<<"\nP%d",i;
if (finish[i] == 1)
{
i = n;
}
}
}
}
}
}
j = 0;
flag = 0;
for (i = 0; i < n; i++)
{
if (finish[i] == 0)
{
dead[j] = i;
j++;
flag = 1;
}
}
if (flag == 1)
{
cout << "\n\nSystem is in Deadlock and the Deadlock
process are\n";
for (i = 0; i < n; i++)
{
cout << "P" << dead[i] << "\t";
}
}
else
{
cout << "\nNo Deadlock Occur";
}
}
int main()
{
int i, j;
cout << "**** Deadlock Detection Algorithm ****\n";
input();
show();
cal();
return 0;
}

Output:

Question 6: Memory Allocation Methods- Best,


Worst and First Fit Algorithms.
//Best Fit:
// C++ implementation of Best - Fit algorithm
#include<iostream>
using namespace std;

// Method to allocate memory to blocks as per Best fit


algorithm
void bestFit(int blockSize[], int m, int processSize[], int
n)
{
// Stores block id of the block allocated to a process
int allocation[n];

// Initially no block is assigned to any process


for (int i = 0; i < n; i++)
allocation[i] = -1;
// pick each process and find suitable blocks
// according to its size ad assign to it
for (int i = 0; i < n; i++)
{
// Find the best fit block for current process
int bestIdx = -1;
for (int j = 0; j < m; j++)
{
if (blockSize[j] >= processSize[i])
{
if (bestIdx == -1)
bestIdx = j;
else if (blockSize[bestIdx] >
blockSize[j])
bestIdx = j;
}
}

// If we could find a block for current process


if (bestIdx != -1)
{
// allocate block j to p[i] process
allocation[i] = bestIdx;

// Reduce available memory in this block.


blockSize[bestIdx] -= processSize[i];
}
}

cout << "\nProcess No.\tProcess Size\tBlock no.\n";


for (int i = 0; i < n; i++)
{
cout << " " << i+1 << "\t\t" << processSize[i] <<
"\t\t";
if (allocation[i] != -1)
cout << allocation[i] + 1;
else
cout << "Not Allocated";
cout << endl;
}
}

// Driver Method
int main()
{
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
int m = sizeof(blockSize) / sizeof(blockSize[0]);
int n = sizeof(processSize) / sizeof(processSize[0]);

bestFit(blockSize, m, processSize, n);

return 0 ;
}

Output:

//Worst Fit:
// C++ implementation of worst - Fit algorithm
#include<bits/stdc++.h>
using namespace std;

// Function to allocate memory to blocks as per worst fit


// algorithm
void worstFit(int blockSize[], int m, int processSize[],

int n)
{
// Stores block id of the block allocated to a
// process
int allocation[n];

// Initially no block is assigned to any process


memset(allocation, -1, sizeof(allocation));

// pick each process and find suitable blocks


// according to its size ad assign to it
for (int i=0; i<n; i++)
{
// Find the best fit block for current process
int wstIdx = -1;
for (int j=0; j<m; j++)
{
if (blockSize[j] >= processSize[i])
{
if (wstIdx == -1)
wstIdx = j;
else if (blockSize[wstIdx] <
blockSize[j])
wstIdx = j;
}
}

// If we could find a block for current process


if (wstIdx != -1)
{
// allocate block j to p[i] process
allocation[i] = wstIdx;

// Reduce available memory in this block.


blockSize[wstIdx] -= processSize[i];
}
}

cout << "\nProcess No.\tProcess Size\tBlock no.\n";


for (int i = 0; i < n; i++)
{
cout << " " << i+1 << "\t\t" << processSize[i] <<
"\t\t";
if (allocation[i] != -1)
cout << allocation[i] + 1;
else
cout << "Not Allocated";
cout << endl;
}
}

// Driver code
int main()
{
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
int m = sizeof(blockSize)/sizeof(blockSize[0]);
int n = sizeof(processSize)/sizeof(processSize[0]);

worstFit(blockSize, m, processSize, n);

return 0 ;
}

Output:

//First Fit:
// C++ implementation of First - Fit algorithm
#include<bits/stdc++.h>
using namespace std;

// Function to allocate memory to


// blocks as per First fit algorithm
void firstFit(int blockSize[], int m,
int processSize[], int n)
{
// Stores block id of the
// block allocated to a process
int allocation[n];

// Initially no block is assigned to any process


memset(allocation, -1, sizeof(allocation));

// pick each process and find suitable blocks


// according to its size ad assign to it
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (blockSize[j] >= processSize[i])
{
// allocate block j to p[i] process
allocation[i] = j;

// Reduce available memory in this block.


blockSize[j] -= processSize[i];

break;
}
}
}

cout << "\nProcess No.\tProcess Size\tBlock no.\n";


for (int i = 0; i < n; i++)
{
cout << " " << i+1 << "\t\t"
<< processSize[i] << "\t\t";
if (allocation[i] != -1)
cout << allocation[i] + 1;
else
cout << "Not Allocated";
cout << endl;
}
}

// Driver code
int main()
{
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
int m = sizeof(blockSize) / sizeof(blockSize[0]);
int n = sizeof(processSize) / sizeof(processSize[0]);

firstFit(blockSize, m, processSize, n);

return 0 ;
}

Output:

Question 7: Implement Page Replacement Algorithms:


LRU, LRU-Approximation, FIFO, Optimal, LFU, Second
Chance, MRU, MFU.
//MFU:
#include <iostream>

using namespace std;

#define FRAMES_NUMBER 3

int MFU(int pages[], int size)


{
// 0) Initialize Frames With '-1'
int frames[FRAMES_NUMBER];
for (int i = 0; i < FRAMES_NUMBER; i++)
frames[i] = -1;

int paeFaults = 0; // Count The Page Faults

// Go Through All Pages


for (int pageIndex = 0; pageIndex < size; pageIndex++)
{

// 1) Find Page In The Frames


bool isFound = false;
for (int i = 0; i < FRAMES_NUMBER; i++)
if (frames[i] == pages[pageIndex])
{
isFound = true;
// Printing
cout << pages[pageIndex] << endl;
break;
}

// If Not Found
if (!isFound)
{
// 2) Find A Free Frame
bool hasFreeFrame = false;
for (int i = 0; i < FRAMES_NUMBER; i++)
if (frames[i] == -1)
{
hasFreeFrame = true;
frames[i] = pages[pageIndex];
paeFaults++;

// Printing
cout << pages[pageIndex] << "\t\t";
for (int f = 0; f < FRAMES_NUMBER; f++)
cout << frames[f] << "\t";
cout << endl;

break;
}

// 3) Page Replacement (Not Found & No Free


Frame)
if (!hasFreeFrame)
{
// Array To Store The Used Count For Each
Page In The Frames
int countUse[FRAMES_NUMBER] = {0};

// Assign Count For Each Page In The Frames


for (int i = 0; i < FRAMES_NUMBER; i++)
for (int p = pageIndex; p >= 0; p--)
if (pages[p] == frames[i])
countUse[i]++;

// Find The Victim Frame (With The Highest


Count)
int victim = 0;
for (int i = 0; i < FRAMES_NUMBER; i++)
if (countUse[i] > countUse[victim])
victim = i;

frames[victim] = pages[pageIndex];
paeFaults++;

// Printing
cout << pages[pageIndex] << "\t\t";
for (int f = 0; f < FRAMES_NUMBER; f++)
cout << frames[f] << "\t";
cout << endl;
}
}
}
return paeFaults;
}

int main(int argc, char const *argv[])


{
int pages[] = {1, 2, 3, 1, 4, 5, 2, 1, 2, 6, 7, 3, 2};

cout << "Number Of Page Faults = " << MFU(pages, 13);

getchar();
return 0;
}

Output:

//MRU:
#include <stdio.h>
#include <stdlib.h>

int find(int no_of_frames, int *frames, int tofound)


{
int index = -1;
for (int i = 0; i < no_of_frames; i++)
{
if (frames[i] == tofound)
{
index = i;
}
}
return index;
}

int traverse(int no_of_pages, int *pageString, int i, int


tofound)
{
int index = -1;
for (int j = i - 1; j >= 0; j--)
{
if (pageString[j] == tofound)
{
return j;
}
}
return index;
}

int find_MRU(int *pageString, int i, int no_of_pages, int


no_of_frames, int *frames)
{
int *flag;
flag = (int *)calloc(no_of_frames, sizeof(int));
for (int j = 0; j < no_of_frames; j++)
{
flag[j] = 0;
}
int index = -1;
int idx = -1;
int max = -1; //just some high value later to be replaced
for (int j = 0; j < no_of_frames; j++)
{
idx = traverse(no_of_pages, pageString, i,
frames[j]);
if (idx != -1)
{
if (idx > max)
{
max = idx;
index = j;
}
flag[j] = 1;
}
}
free(flag);
return index;
}

int main()
{
int no_of_frames, no_of_pages;
printf("Enter the no of frames:\n");
scanf("%d", &no_of_frames);
printf("Enter the no of pages:\n");
scanf("%d", &no_of_pages);
printf("Enter the pageString\n");
int *pageString;
pageString = (int *)calloc(no_of_pages, sizeof(int));
for (int i = 0; i < no_of_pages; i++)
{
scanf("%d", &pageString[i]);
}
int *frames;
frames = (int *)calloc(no_of_frames, sizeof(int));
for (int i = 0; i < no_of_frames; i++)
{
frames[i] = -1;
}
int index = 0;
int no_of_page_faults = 0;
int no_of_page_hits = 0;
int idx;
int count = 0;
for (int i = 0; i < no_of_pages; i++)
{
if (count < no_of_frames)
{
idx = find(no_of_frames, frames, pageString[i]);
if (idx != -1)
{
no_of_page_hits++;
printf("Page Hit : Succesfully found Page %d
at %d Frame\n", pageString[i], idx + 1);
}
else
{
frames[count] = pageString[i];
printf("Page Miss : Storing %d Page no in %d
Frame:\n", pageString[i], count + 1);
count++;
no_of_page_faults++;
}
}
else
{
idx = find(no_of_frames, frames, pageString[i]);
if (idx != -1)
{
no_of_page_hits++;
printf("Page Hit : Succesfully found Page %d
at %d Frame\n", pageString[i], idx + 1);
}
else
{
index = find_MRU(pageString, i, no_of_pages,
no_of_frames, frames);
printf("Page Miss : Replacing %d Frame Page
with %d Page no:\n", index + 1, pageString[i]);
no_of_page_faults++;
frames[index] = pageString[i];
}
}
}
printf("The total number of page faults are : %d\n",
no_of_page_faults);
printf("The total number of page hits are : %d\n",
no_of_page_hits);
return 0;
}

Output:

//Second Chance:
// CPP program to find largest in an array
// without conditional/bitwise/ternary/ operators
// and without library functions.
#include<iostream>
#include<cstring>
#include<sstream>
using namespace std;

// If page found, updates the second chance bit to true


static bool findAndUpdate(int x,int arr[],
bool second_chance[],int frames)

{
int i;

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


{

if(arr[i] == x)
{
// Mark that the page deserves a second
chance
second_chance[i] = true;

// Return 'true', that is there was a hit


// and so there's no need to replace any
page
return true;
}
}

// Return 'false' so that a page for replacement is


selected
// as he reuested page doesn't exist in memory
return false;

// Updates the page in memory and returns the pointer


static int replaceAndUpdate(int x,int arr[],
bool second_chance[],int frames,int
pointer)
{
while(true)
{

// We found the page to replace


if(!second_chance[pointer])
{
// Replace with new page
arr[pointer] = x;

// Return updated pointer


return (pointer + 1) % frames;
}

// Mark it 'false' as it got one chance


// and will be replaced next time unless
accessed again
second_chance[pointer] = false;

//Pointer is updated in round robin manner


pointer = (pointer + 1) % frames;
}
}

static void printHitsAndFaults(string reference_string,


int
frames)
{
int pointer, i, l=0, x, pf;

//initially we consider frame 0 is to be replaced


pointer = 0;
//number of page faults
pf = 0;

// Create a array to hold page numbers


int arr[frames];

// No pages initially in frame,


// which is indicated by -1
memset(arr, -1, sizeof(arr));

// Create second chance array.


// Can also be a byte array for optimizing memory
bool second_chance[frames];

// Split the string into tokens,


// that is page numbers, based on space

string str[100];
string word = "";
for (auto x : reference_string)
{
if (x == ' ')
{
str[l]=word;
word = "";
l++;
}
else
{
word = word + x;
}
}
str[l] = word;
l++;
// l=the length of array
for(i = 0; i < l; i++)
{
x = stoi(str[i]);

// Finds if there exists a need to replace


// any page at all
if(!findAndUpdate(x,arr,second_chance,frames))
{
// Selects and updates a victim page
pointer = replaceAndUpdate(x,arr,
second_chance,frames,pointer);

// Update page faults


pf++;
}
}
cout << "Total page faults were " << pf << "\n";
}

// Driver code
int main()
{
string reference_string = "";
int frames = 0;

// Test 1:
reference_string = "0 4 1 4 2 4 3 4 2 4 0 4 1 4 2 4
3 4";
frames = 3;

// Output is 9
printHitsAndFaults(reference_string,frames);

// Test 2:
reference_string = "2 5 10 1 2 2 6 9 1 2 10 2 6 1 2
1 6 9 5 1";
frames = 4;

// Output is 11
printHitsAndFaults(reference_string,frames);
return 0;
}

Output:

//LFU:
// C++ program for LFU cache implementation
#include <bits/stdc++.h>
using namespace std;

// Generic function to swap two pairs


void swap(pair<int, int>& a, pair<int, int>& b)
{
pair<int, int> temp = a;
a = b;
b = temp;
}

// Returns the index of the parent node


inline int parent(int i)
{
return (i - 1) / 2;
}

// Returns the index of the left child node


inline int left(int i)
{
return 2 * i + 1;
}

// Returns the index of the right child node


inline int right(int i)
{
return 2 * i + 2;
}

// Self made heap to Rearranges


// the nodes in order to maintain the heap property
void heapify(vector<pair<int, int> >& v,
unordered_map<int, int>& m, int i, int n)
{
int l = left(i), r = right(i), minim;
if (l < n)
minim = ((v[i].second < v[l].second) ? i : l);
else
minim = i;
if (r < n)
minim = ((v[minim].second < v[r].second) ? minim :
r);
if (minim != i) {
m[v[minim].first] = i;
m[v[i].first] = minim;
swap(v[minim], v[i]);
heapify(v, m, minim, n);
}
}

// Function to Increment the frequency


// of a node and rearranges the heap
void increment(vector<pair<int, int> >& v,
unordered_map<int, int>& m, int i, int n)
{
++v[i].second;
heapify(v, m, i, n);
}

// Function to Insert a new node in the heap


void insert(vector<pair<int, int> >& v,
unordered_map<int, int>& m, int value, int& n)
{

if (n == v.size()) {
m.erase(v[0].first);
cout << "Cache block " << v[0].first
<< " removed.\n";
v[0] = v[--n];
heapify(v, m, 0, n);
}
v[n++] = make_pair(value, 1);
m.insert(make_pair(value, n - 1));
int i = n - 1;

// Insert a node in the heap by swapping elements


while (i && v[parent(i)].second > v[i].second) {
m[v[i].first] = parent(i);
m[v[parent(i)].first] = i;
swap(v[i], v[parent(i)]);
i = parent(i);
}
cout << "Cache block " << value << " inserted.\n";
}

// Function to refer to the block value in the cache


void refer(vector<pair<int, int> >& cache, unordered_map<int,
int>& indices, int value, int&
cache_size)
{
if (indices.find(value) == indices.end())
insert(cache, indices, value, cache_size);
else
increment(cache, indices, indices[value],
cache_size);
}
// Driver Code
int main()
{
int cache_max_size = 4, cache_size = 0;
vector<pair<int, int> > cache(cache_max_size);
unordered_map<int, int> indices;
refer(cache, indices, 1, cache_size);
refer(cache, indices, 2, cache_size);
refer(cache, indices, 1, cache_size);
refer(cache, indices, 3, cache_size);
refer(cache, indices, 2, cache_size);
refer(cache, indices, 4, cache_size);
refer(cache, indices, 5, cache_size);
return 0;
}

Output:

//LRU Algo
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,m,i,j,k,hit=0;
cout<<"Enter number of frames\n";
cin>>n;
cout<<"Enter number of processes\n";
cin>>m;
vector<int> p(m);
vector<int> hi(m);
cout<<"Enter processes\n";
for(i=0;i<m;i++){
cin>>p[i];
}
vector<vector<int>> a(n);
for(i=0;i<n;i++){
a[i]=vector<int>(m,-1);
}
map <int, int> mp;
for(i=0;i<m;i++){
vector<pair<int,int>> c;
for(auto q: mp){
c.push_back({q.second,q.first});
}
sort(c.begin(),c.end());
bool hasrun=false;
for(j=0;j<n;j++){
if(a[j][i]==p[i]){
hit++;
hi[i]=1;
mp[p[i]]=1;
hasrun=true;
break;
}
if(a[j][i]==-1){
for(k=i;k<m;k++)
a[j][k]=p[i];
mp[p[i]]++;
hasrun=true;
break;
}
}
if(j==n||hasrun==false){
for(j=0;j<n;j++){
if(a[j][i]==c[c.size()-1].second){
mp.erase(a[j][i]);
for(k=i;k<m;k++)
a[j][k]=p[i];
mp[p[i]]++;
break;
}
}
}
for(auto q:mp){
if(q.first!=p[i]){
mp[q.first]++;
}
}
}
cout<<"Process ";
for(i=0;i<m;i++){
cout<<p[i]<<" ";
}
cout<<'\n';
for(i=0;i<n;i++){
cout<<"Frame "<<i<<" ";
for(j=0;j<m;j++){
if(a[i][j]==-1)
cout<<"E ";
else
cout<<a[i][j]<<" ";
}
cout<<'\n';
}
for(i=0;i<m;i++){
if(hi[i]==0)
cout<<" ";
else
cout<<hi[i]<<" ";
}
cout<<"\n";
cout<<"Hit "<<hit<<'\n'<<"Page Fault "<<m-hit<<'\n';
return 0;
}

//FIFO Algo
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,m,i,j,k,hit=0;
cout<<"Enter number of frames\n";
cin>>n;
cout<<"Enter number of processes\n";
cin>>m;
vector<int> p(m);
vector<int> hi(m);
cout<<"Enter processes\n";
for(i=0;i<m;i++){
cin>>p[i];
}
vector<vector<int>> a(n);
for(i=0;i<n;i++){
a[i]=vector<int>(m,-1);
}
map <int, int> mp;
for(i=0;i<m;i++){
vector<pair<int,int>> c;
for(auto q: mp){
c.push_back({q.second,q.first});
}
sort(c.begin(),c.end());
bool hasrun=false;
for(j=0;j<n;j++){
if(a[j][i]==p[i]){
hit++;
hi[i]=1;
mp[p[i]]++;
hasrun=true;
break;
}
if(a[j][i]==-1){
for(k=i;k<m;k++)
a[j][k]=p[i];
mp[p[i]]++;
hasrun=true;
break;
}
}
if(j==n||hasrun==false){
for(j=0;j<n;j++){
if(a[j][i]==c[c.size()-1].second){
mp.erase(a[j][i]);
for(k=i;k<m;k++)
a[j][k]=p[i];
mp[p[i]]++;
break;
}
}
}
for(auto q:mp){
if(q.first!=p[i]){
mp[q.first]++;
}
}
}
cout<<"Process ";
for(i=0;i<m;i++){
cout<<p[i]<<" ";
}
cout<<'\n';
for(i=0;i<n;i++){
cout<<"Frame "<<i<<" ";
for(j=0;j<m;j++){
if(a[i][j]==-1)
cout<<"E ";
else
cout<<a[i][j]<<" ";
}
cout<<'\n';
}
for(i=0;i<m;i++){
if(hi[i]==0)
cout<<" ";
else
cout<<hi[i]<<" ";
}
cout<<"\n";
cout<<"Hit "<<hit<<'\n'<<"Page Fault "<<m-hit<<'\n';
return 0;
}

//Optimal Page Replacement Algo


#include<bits/stdc++.h>
using namespace std;
int main(){
int n,m,i,j,k;
cout<<"Enter number of frames\n";
cin>>n;
cout<<"Enter number of processes\n";
cin>>m;
vector<int> p(m);
cout<<"Enter processes\n";
for(i=0;i<m;i++){
cin>>p[i];
}
vector<vector<int>> a(n,vector<int>(m,-1));
map <int, int> mp;
for(i=0;i<m;i++){
vector<int> op;
vector<pair<int,int>> c;
for(auto q: mp){
c.push_back({q.second,q.first});
}
for(int q=i+1;q<m;q++){
for(j=0;j<n;j++){
if(a[j][i]==p[q]){
op.push_back(p[q]);
}
}
}
sort(op.begin(),op.end());
op.erase(unique(op.begin(),op.end()),op.end());
bool dontCall=true;
if(op.size()==n){
dontCall=false;
}
sort(c.begin(),c.end());
bool hasrun=false;
for(j=0;j<n;j++){
if(a[j][i]==p[i]){
mp[p[i]]++;
hasrun=true;
break;
}
if(a[j][i]==-1){
for(k=i;k<m;k++)
a[j][k]=p[i];
mp[p[i]]++;
hasrun=true;
break;
}
}
if(j==n||hasrun==false){
for(j=0;j<n;j++){
if(dontCall==true){
if(a[j][i]==c[c.size()-1].second){
mp.erase(a[j][i]);
for(k=i;k<m;k++)
a[j][k]=p[i];
mp[p[i]]++;
break;
}
}
else if(dontCall==false){
if(a[j][i]==op[op.size()-1]){
mp.erase(a[j][i]);
for(k=i;k<m;k++)
a[j][k]=p[i];
mp[p[i]]++;
break;
}
}
}
}
for(auto q:mp){
if(q.first!=p[i]){
mp[q.first]++;
}
}
}
int hit=0;
vector<int> hitv(m);
for(i=1;i<m;i++){
for(j=0;j<n;j++){
if(p[i]==a[j][i-1]){
hit++;
hitv[i]=1;
break;
}
}
}
cout<<"Process ";
for(i=0;i<m;i++){
cout<<p[i]<<" ";
}
cout<<'\n';
for(i=0;i<n;i++){
cout<<"Frame "<<i<<" ";
for(j=0;j<m;j++){
if(a[i][j]==-1)
cout<<"E ";
else
cout<<a[i][j]<<" ";
}
cout<<'\n';
}
cout<<"HIT ";
for(i=0;i<hitv.size();i++){
if(hitv[i]==0)
cout<<" ";
else
cout<<hitv[i]<<" ";
}
cout<<"\n";
cout<<"Hit "<<hit<<'\n'<<"Page Fault "<<m-hit<<'\n';
return 0;
}
//Second-Chance Algo(LRU Approximation)
#include<iostream>
#include<cstring>
#include<sstream>
using namespace std;

static bool findAndUpdate(int x,int arr[],


bool second_chance[],int frames)

{
int i;

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


{

if(arr[i] == x)
{

second_chance[i] = true;

return true;
}
}

return false;

static int replaceAndUpdate(int x,int arr[],


bool second_chance[],int frames,int pointer)
{
while(true)
{

if(!second_chance[pointer])
{

arr[pointer] = x;

return (pointer + 1) % frames;


}

second_chance[pointer] = false;

pointer = (pointer + 1) % frames;


}
}

static void printHitsAndFaults(string reference_string,


int frames)
{
int pointer, i, l=0, x, pf;

pointer = 0;

pf = 0;

int arr[frames];

memset(arr, -1, sizeof(arr));


bool second_chance[frames];

string str[100];
string word = "";
for (auto x : reference_string)
{
if (x == ' ')
{
str[l]=word;
word = "";
l++;
}
else
{
word = word + x;
}
}
str[l] = word;
l++;

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


{
x = stoi(str[i]);

if(!findAndUpdate(x,arr,second_chance,frames))
{

pointer = replaceAndUpdate(x,arr,
second_chance,frames,pointer);

pf++;
}
}
cout << "Total page faults were " << pf << "\n";
}

// Driver code
int main()
{
string reference_string = "";
int frames = 0;

// Test 1:
reference_string = "0 4 1 4 2 4 3 4 2 4 0 4 1 4 2 4 3 4";
frames = 3;

// Output is 9
printHitsAndFaults(reference_string,frames);

// Test 2:
reference_string = "2 5 10 1 2 2 6 9 1 2 10 2 6 1 2 1 6 9 5
1";
frames = 4;

// Output is 12
printHitsAndFaults(reference_string,frames);
return 0;
}

Output:

LRU:
FIFO:

Optimal Page Replacement:

Second Chance Algorithm:

Question 8: Implement Disk Scheduling Algorithms: FCFS, SSTF, SCAN,


C-SCAN, LOOK, C-LOOK.
//FCFS Disk Scheduling Algo
#include <bits/stdc++.h>
using namespace std;

int size = 8;
void FCFS(int arr[], int head)
{
int seek_count = 0;
int distance, cur_track;

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


cur_track = arr[i];

distance = abs(cur_track - head);

seek_count += distance;

head = cur_track;
}

cout << "Total number of seek operations = "


<< seek_count << endl;

// Seek sequence would be the same


// as request array sequence
cout << "Seek Sequence is" << endl;

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


cout << arr[i] << endl;
}
}

// Driver code
int main()
{

// request array
int arr[size] = { 176, 79, 34, 60, 92, 11, 41, 114 };
int head = 50;

FCFS(arr, head);
return 0;
}

// SSTF Disk Scheduling Algo


#include <bits/stdc++.h>
using namespace std;

void calculatedifference(int request[], int head,int diff[]


[2], int n)
{
for(int i = 0; i < n; i++)
{
diff[i][0] = abs(head - request[i]);
}
}

int findMIN(int diff[][2], int n)


{
int index = -1;
int minimum = 1e9;

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


{
if (!diff[i][1] && minimum > diff[i][0])
{
minimum = diff[i][0];
index = i;
}
}
return index;
}

void shortestSeekTimeFirst(int request[], int head, int n)


{
if (n == 0)
{
return;
}

int diff[n][2] = { { 0, 0 } };

int seekcount = 0;

int seeksequence[n + 1] = {0};

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


{
seeksequence[i] = head;
calculatedifference(request, head, diff, n);
int index = findMIN(diff, n);
diff[index][1] = 1;

seekcount += diff[index][0];

head = request[index];
}
seeksequence[n] = head;

cout << "Total number of seek operations = "


<< seekcount << endl;
cout << "Seek sequence is : " << "\n";

// Print the sequence


for(int i = 0; i <= n; i++)
{
cout << seeksequence[i] << "\n";
}
}

// Driver code
int main()
{
int n = 8;
int proc[n] = { 176, 79, 34, 60, 92, 11, 41, 114 };

shortestSeekTimeFirst(proc, 50, n);

return 0;
}

// SCAN Disk Scheduling algorithm


#include <bits/stdc++.h>
using namespace std;

int size = 8;
int disk_size = 200;

void SCAN(int arr[], int head, string direction)


{
int seek_count = 0;
int distance, cur_track;
vector<int> left, right;
vector<int> seek_sequence;

if (direction == "left")
left.push_back(0);
else if (direction == "right")
right.push_back(disk_size - 1);

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


if (arr[i] < head)
left.push_back(arr[i]);
if (arr[i] > head)
right.push_back(arr[i]);
}

std::sort(left.begin(), left.end());
std::sort(right.begin(), right.end());

int run = 2;
while (run--) {
if (direction == "left") {
for (int i = left.size() - 1; i >= 0; i--) {
cur_track = left[i];

seek_sequence.push_back(cur_track);

distance = abs(cur_track - head);

seek_count += distance;

head = cur_track;
}
direction = "right";
}
else if (direction == "right") {
for (int i = 0; i < right.size(); i++) {
cur_track = right[i];

seek_sequence.push_back(cur_track);

distance = abs(cur_track - head);

seek_count += distance;

head = cur_track;
}
direction = "left";
}
}

cout << "Total number of seek operations = "


<< seek_count << endl;

cout << "Seek Sequence is" << endl;

for (int i = 0; i < seek_sequence.size(); i++) {


cout << seek_sequence[i] << endl;
}
}

// Driver code
int main()
{

// request array
int arr[size] = { 176, 79, 34, 60,
92, 11, 41, 114 };
int head = 50;
string direction = "left";

SCAN(arr, head, direction);

return 0;
}

// C-SCAN Disk Scheduling Algo


#include <bits/stdc++.h>
using namespace std;

int size = 8;
int disk_size = 200;

void CSCAN(int arr[], int head)


{
int seek_count = 0;
int distance, cur_track;
vector<int> left, right;
vector<int> seek_sequence;

left.push_back(0);
right.push_back(disk_size - 1);

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


if (arr[i] < head)
left.push_back(arr[i]);
if (arr[i] > head)
right.push_back(arr[i]);
}

std::sort(left.begin(), left.end());
std::sort(right.begin(), right.end());

for (int i = 0; i < right.size(); i++) {


cur_track = right[i];

seek_sequence.push_back(cur_track);

distance = abs(cur_track - head);

seek_count += distance;

head = cur_track;
}

head = 0;
seek_count += (disk_size - 1);

for (int i = 0; i < left.size(); i++) {


cur_track = left[i];

seek_sequence.push_back(cur_track);

distance = abs(cur_track - head);

seek_count += distance;

head = cur_track;
}

cout << "Total number of seek operations = "


<< seek_count << endl;

cout << "Seek Sequence is" << endl;

for (int i = 0; i < seek_sequence.size(); i++) {


cout << seek_sequence[i] << endl;
}
}

// Driver code
int main()
{

// request array
int arr[size] = { 176, 79, 34, 60, 92, 11, 41, 114 };
int head = 50;
cout << "Initial position of head: " << head << endl;
CSCAN(arr, head);

return 0;
}

// LOOK Disk Scheduling Algo


int size = 8;
#include <bits/stdc++.h>
using namespace std;

int disk_size = 200;

void LOOK(int arr[], int head, string direction)


{
int seek_count = 0;
int distance, cur_track;
vector<int> left, right;
vector<int> seek_sequence;

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


if (arr[i] < head)
left.push_back(arr[i]);
if (arr[i] > head)
right.push_back(arr[i]);
}

std::sort(left.begin(), left.end());
std::sort(right.begin(), right.end());

int run = 2;
while (run--) {
if (direction == "left") {
for (int i = left.size() - 1; i >= 0; i--) {
cur_track = left[i];
seek_sequence.push_back(cur_track);

distance = abs(cur_track - head);

seek_count += distance;

head = cur_track;
}

direction = "right";
}
else if (direction == "right") {
for (int i = 0; i < right.size(); i++) {
cur_track = right[i];

seek_sequence.push_back(cur_track);

distance = abs(cur_track - head);

seek_count += distance;

head = cur_track;
}

direction = "left";
}
}

cout << "Total number of seek operations = "


<< seek_count << endl;
cout << "Seek Sequence is" << endl;

for (int i = 0; i < seek_sequence.size(); i++) {


cout << seek_sequence[i] << endl;
}
}

// Driver code
int main()
{

// request array
int arr[size] = { 176, 79, 34, 60,
92, 11, 41, 114 };
int head = 50;
string direction = "right";

cout << "Initial position of head: "


<< head << endl;

LOOK(arr, head, direction);

return 0;
}

//C-LOOK Algo
#include <bits/stdc++.h>
using namespace std;
int size = 8;
int disk_size = 200;

void CLOOK(int arr[], int head)


{
int seek_count = 0;
int distance, cur_track;
vector<int> left, right;
vector<int> seek_sequence;
for (int i = 0; i < size; i++) {
if (arr[i] < head)
left.push_back(arr[i]);
if (arr[i] > head)
right.push_back(arr[i]);
}

std::sort(left.begin(), left.end());
std::sort(right.begin(), right.end());

for (int i = 0; i < right.size(); i++) {


cur_track = right[i];

seek_sequence.push_back(cur_track);

distance = abs(cur_track - head);

seek_count += distance;

head = cur_track;
}

seek_count += abs(head - left[0]);


head = left[0];

for (int i = 0; i < left.size(); i++) {


cur_track = left[i];

seek_sequence.push_back(cur_track);
distance = abs(cur_track - head);

seek_count += distance;

head = cur_track;
}

cout << "Total number of seek operations = "


<< seek_count << endl;

cout << "Seek Sequence is" << endl;

for (int i = 0; i < seek_sequence.size(); i++) {


cout << seek_sequence[i] << endl;
}
}

// Driver code
int main()
{
// Request array
int arr[size] = { 176, 79, 34, 60,
92, 11, 41, 114 };
int head = 50;

cout << "Initial position of head: " << head << endl;

CLOOK(arr, head);

return 0;
}

Output:

FCFS:
SSTF:

SCAN:

C-SCAN:

LOOK:

C-LOOK:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy