You are on page 1of 38

NAME:​ P

​ ​ OOJA KUMARI
BATCH​: ​2018-22
STREAM:​ ​CSE
ENROLLMENT NO:​ ​12018002001088(SEC-B)
SUBJECT NAME:​ ​OPERATING SYSTEM LAB
SUBJECT CODE:​ C
​ SC590
Assignment-1(a): Write a C program to create child process from
a parent process using fork().

#include<unistd.h>
#include<stdio.h>
int main()
{
int pid;
pid=fork();
if(pid<0)
printf("fork error");
if(pid==0)
{
printf("\nThis is child process");
printf("\nChild PID: %d", getpid());
printf("\nParent PID: %d", getppid());
execlp("/bin/ls",NULL);
exit(0);
}
else
{
wait(NULL);
printf("\nThis is parent process");
printf("\nParent PID: %d", getpid());
printf("\nChild PID: %d", pid);
exit(0);
}
}

OUTPUT:->

This is child process


Child PID: 3122
Parent PID: 3121

This is parent process


Parent PID: 3121
Child PID: 3122
Assingment-1(b): Write a C program to create four processes (1
parent & 3 children) where they terminate in a sequence as
follows: 1. Third child should be terminating first. 2. Second child
should be terminated after last and before first child 3. Parent
process should be terminating in last. 4. First child should be
terminated before parent & after second child.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
int pid, pid1, pid2;

pid = fork();

if (pid == 0) {

sleep(3);

printf("child[1] --> pid = %d and ppid = %d\n",


getpid(), getppid());
}

else {
pid1 = fork();
if (pid1 == 0) {
sleep(2);
printf("child[2] --> pid = %d and ppid = %d\n",
getpid(), getppid());
}
else {
pid2 = fork();
if (pid2 == 0) {

printf("child[3] --> pid = %d and ppid = %d\n",


getpid(), getppid());
}

else {

sleep(3);
printf("parent --> pid = %d\n", getpid());
}
}
}

return 0;
}

OUTPUT:

child[3]-->pid=50 and ppid=47


child[2]-->pid=49 and ppid=47
child[1]-->pid=48 and ppid=47
parent-->pid=47

Experiment-1(c): Calculate the sum of odd and even Number


using fork() system call

#include <iostream>
#include <unistd.h>
using namespace std;

int main()
{
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sumOdd = 0, sumEven = 0, n, i;
n = fork();

if (n > 0) {
for (i = 0; i < 10; i++) {
if (a[i] % 2 == 0)
sumEven = sumEven + a[i];
}
cout << "Parent process \n";
cout << "Sum of even no. is " << sumEven << endl;
}

else {
for (i = 0; i < 10; i++) {
if (a[i] % 2 != 0)
sumOdd = sumOdd + a[i];
}
cout << "Child process \n";
cout << "\nSum of odd no. is " << sumOdd << endl;
}
return 0;
}

OUTPUT:
Assignmemt-2(a): Write a C Program to implement the FCFS
process scheduling mechanism. Print the followings: 1. Average
turnaround time 2. Average waiting time Find the problem from
the attachment
#include<iostream>
using namespace std;

void findWaitingTime(int processes[], int n, int bt[],


int wt[], int at[])
{
int service_time[n];
service_time[0] = 0;
wt[0] = 0;

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


{

service_time[i] = service_time[i-1] + bt[i-1];

wt[i] = service_time[i] - at[i];

if (wt[i] < 0)
wt[i] = 0;
}
}

void findTurnAroundTime(int processes[], int n, int bt[],


int wt[], int tat[])
{

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


tat[i] = bt[i] + wt[i];
}

void findavgTime(int processes[], int n, int bt[], int at[])


{
int wt[n], tat[n];

findWaitingTime(processes, n, bt, wt, at);

findTurnAroundTime(processes, n, bt, wt, tat);

cout << "Processes " << " Burst Time " << " Arrival Time "
<< " Waiting Time " << " Turn-Around Time "
<< " Completion Time \n";
int total_wt = 0, total_tat = 0;
for (int i = 0 ; i < n ; i++)
{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
int compl_time = tat[i] + at[i];
cout << " " << i+1 << "\t\t" << bt[i] << "\t\t"
<< at[i] << "\t\t" << wt[i] << "\t\t "
<< tat[i] << "\t\t " << compl_time << endl;
}

cout << "Average waiting time = "


<< (float)total_wt / (float)n;
cout << "\nAverage turn around time = "
<< (float)total_tat / (float)n;
}

int main()
{

int processes[] = {1, 2, 3};


int n = sizeof processes / sizeof processes[0];

int burst_time[] = {3, 8, 5};

int arrival_time[] = {0, 1, 2};

findavgTime(processes, n, burst_time, arrival_time);

return 0;
}
Output:
Assignmemt-2(b): Write a C Program to implement the SJF
process scheduling mechanism. Print the followings: 1. Average
turnaround time 2. Average waiting time

#include <stdio.h>

int main()
{
int arrival_time[10], burst_time[10], temp[10];
int i, smallest, count = 0, time, limit;
double wait_time = 0, turnaround_time = 0, end;
float average_waiting_time, average_turnaround_time;
printf("Enter the Total Number of Processes:t");
scanf("%d", &limit);
printf("Enter Details of %d Processesn", limit);
for(i = 0; i < limit; i++)
{
printf("nEnter Arrival Time:t");
scanf("%d", &arrival_time[i]);
printf("Enter Burst Time:t");
scanf("%d", &burst_time[i]);
temp[i] = burst_time[i];
}
burst_time[9] = 9999;
for(time = 0; count != limit; time++)
{
smallest = 9;
for(i = 0; i < limit; i++)
{
if(arrival_time[i] <= time && burst_time[i] < burst_time[smallest] &&
burst_time[i] > 0)
{
smallest = i;
}
}
burst_time[smallest]--;
if(burst_time[smallest] == 0)
{
count++;
end = time + 1;
wait_time = wait_time + end - arrival_time[smallest] - temp[smallest];
turnaround_time = turnaround_time + end - arrival_time[smallest];
}
}
average_waiting_time = wait_time / limit;
average_turnaround_time = turnaround_time / limit;
printf("Average Waiting Time:t%lfn", average_waiting_time);
printf("Average Turnaround Time:t%lfn", average_turnaround_time);
return 0;
}

OUTPUT:
Assignmemt-2(c): Write a C Program to implement the
preemptive SJF( SRTF) process scheduling mechanism. Print the
followings: 1. Average turnaround time 2. Average waiting time

#include <stdio.h>

int main()
{
int arrival_time[10], burst_time[10], temp[10];
int i, smallest, count = 0, time, limit;
double wait_time = 0, turnaround_time = 0, end;
float average_waiting_time, average_turnaround_time;
printf("nEnter the Total Number of Processes:t");
scanf("%d", &limit);
printf("nEnter Details of %d Processesn", limit);
for(i = 0; i < limit; i++)
{
printf("nEnter Arrival Time:t");
scanf("%d", &arrival_time[i]);
printf("Enter Burst Time:t");
scanf("%d", &burst_time[i]);
temp[i] = burst_time[i];
}
burst_time[9] = 9999;
for(time = 0; count != limit; time++)
{
smallest = 9;
for(i = 0; i < limit; i++)
{
if(arrival_time[i] <= time && burst_time[i] < burst_time[smallest] &&
burst_time[i] > 0)
{
smallest = i;
}
}
burst_time[smallest]--;
if(burst_time[smallest] == 0)
{
count++;
end = time + 1;
wait_time = wait_time + end - arrival_time[smallest] - temp[smallest];
turnaround_time = turnaround_time + end - arrival_time[smallest];
}
}
average_waiting_time = wait_time / limit;
average_turnaround_time = turnaround_time / limit;
printf("nnAverage Waiting Time:t%lfn", average_waiting_time);
printf("Average Turnaround Time:t%lfn", average_turnaround_time);
return 0;
}

OUTPUT:
Assignmemt-2(d): Write a C Program to implement the round
robin ( RR) process scheduling mechanism. Print the followings:
1. Average turnaround time 2. Average waiting time

PROGRAM:

#include<stdio.h>

int main()
{
int i, limit, total = 0, x, counter = 0, time_quantum;
int wait_time = 0, turnaround_time = 0, arrival_time[10], burst_time[10], temp[10];
float average_wait_time, average_turnaround_time;
printf("\nEnter Total Number of Processes:\t");
scanf("%d", &limit);
x = limit;
for(i = 0; i < limit; i++)
{
printf("\nEnter Details of Process[%d]\n", i + 1);
printf("Arrival Time:\t");
scanf("%d", &arrival_time[i]);
printf("Burst Time:\t");
scanf("%d", &burst_time[i]);
temp[i] = burst_time[i];
}
printf("\nEnter Time Quantum:\t");
scanf("%d", &time_quantum);
printf("\nProcess ID\t\tBurst Time\t Turnaround Time\t Waiting Time\n");
for(total = 0, i = 0; x != 0;)
{
if(temp[i] <= time_quantum && temp[i] > 0)
{
total = total + temp[i];
temp[i] = 0;
counter = 1;
}
else if(temp[i] > 0)
{
temp[i] = temp[i] - time_quantum;
total = total + time_quantum;
}
if(temp[i] == 0 && counter == 1)
{
x--;
printf("\nProcess[%d]\t\t%d\t\t %d\t\t\t %d", i + 1, burst_time[i], total -
arrival_time[i], total - arrival_time[i] - burst_time[i]);
wait_time = wait_time + total - arrival_time[i] - burst_time[i];
turnaround_time = turnaround_time + total - arrival_time[i];
counter = 0;
}
if(i == limit - 1)
{
i = 0;
}
else if(arrival_time[i + 1] <= total)
{
i++;
}
else
{
i = 0;
}
}
average_wait_time = wait_time * 1.0 / limit;
average_turnaround_time = turnaround_time * 1.0 / limit;
printf("\n\nAverage Waiting Time:\t%f", average_wait_time);
printf("\nAvg Turnaround Time:\t%f\n", average_turnaround_time);
return 0;
}

OUTPUT:
Assignment-2(e): Write a C Program to implement the priority
scheduling mechanism. Priority Oder: 1>2>3>4 Print the
followings: 1. Average turnaround time 2. Average waiting time

PROGRAM:

#include<stdio.h>

int main()
{
int bt[20],p[20],wt[20],tat[20],pr[20],i,j,n,total=0,pos,temp,avg_wt,avg_tat;
printf("Enter Total Number of Process:");
scanf("%d",&n);

printf("\nEnter Burst Time and Priority\n");


for(i=0;i<n;i++)
{
printf("\nP[%d]\n",i+1);
printf("Burst Time:");
scanf("%d",&bt[i]);
printf("Priority:");
scanf("%d",&pr[i]);
p[i]=i+1; //contains process number
}

//sorting burst time, priority and process number in ascending order using selection
sort
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(pr[j]<pr[pos])
pos=j;
}

temp=pr[i];
pr[i]=pr[pos];
pr[pos]=temp;

temp=bt[i];
bt[i]=bt[pos];
bt[pos]=temp;

temp=p[i];
p[i]=p[pos];
p[pos]=temp;
}

wt[0]=0; //waiting time for first process is zero

//calculate waiting time


for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];

total+=wt[i];
}

avg_wt=total/n; //average waiting time


total=0;

printf("\nProcess\t Burst Time \tWaiting Time\tTurnaround Time");


for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i]; //calculate turnaround time
total+=tat[i];
printf("\nP[%d]\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}

avg_tat=total/n; //average turnaround time


printf("\n\nAverage Waiting Time=%d",avg_wt);
printf("\nAverage Turnaround Time=%d\n",avg_tat);

return 0;
}

OUTPUT:
Assignment-2(f): Preemptive Priority Scheduling Algorithm: Write
a C Program to implement the preemptive priority scheduling
mechanism. Priority Oder: 1>2>3>4 Print the followings: 1.
Average turnaround time 2. Average waiting time

PROGRAM:

#include<stdio.h>

struct process
{
char process_name;
int arrival_time, burst_time, ct, waiting_time, turnaround_time, priority;
int status;
}process_queue[10];

int limit;

void Arrival_Time_Sorting()
{
struct process temp;
int i, j;
for(i = 0; i < limit - 1; i++)
{
for(j = i + 1; j < limit; j++)
{
if(process_queue[i].arrival_time > process_queue[j].arrival_time)
{
temp = process_queue[i];
process_queue[i] = process_queue[j];
process_queue[j] = temp;
}
}
}
}

int main()
{
int i, time = 0, burst_time = 0, largest;
char c;
float wait_time = 0, turnaround_time = 0, average_waiting_time,
average_turnaround_time;
printf("\nEnter Total Number of Processes:\t");
scanf("%d", &limit);
for(i = 0, c = 'A'; i < limit; i++, c++)
{
process_queue[i].process_name = c;
printf("\nEnter Details For Process[%C]:\n", process_queue[i].process_name);
printf("Enter Arrival Time:\t");
scanf("%d", &process_queue[i].arrival_time );
printf("Enter Burst Time:\t");
scanf("%d", &process_queue[i].burst_time);
printf("Enter Priority:\t");
scanf("%d", &process_queue[i].priority);
process_queue[i].status = 0;
burst_time = burst_time + process_queue[i].burst_time;
}
Arrival_Time_Sorting();
process_queue[9].priority = -9999;
printf("\nProcess Name\tArrival Time\tBurst Time\tPriority\tWaiting Time");
for(time = process_queue[0].arrival_time; time < burst_time;)
{
largest = 9;
for(i = 0; i < limit; i++)
{
if(process_queue[i].arrival_time <= time && process_queue[i].status != 1 &&
process_queue[i].priority > process_queue[largest].priority)
{
largest = i;
}
}
time = time + process_queue[largest].burst_time;
process_queue[largest].ct = time;
process_queue[largest].waiting_time = process_queue[largest].ct -
process_queue[largest].arrival_time - process_queue[largest].burst_time;
process_queue[largest].turnaround_time = process_queue[largest].ct -
process_queue[largest].arrival_time;
process_queue[largest].status = 1;
wait_time = wait_time + process_queue[largest].waiting_time;
turnaround_time = turnaround_time + process_queue[largest].turnaround_time;
printf("\n%c\t\t%d\t\t%d\t\t%d\t\t%d", process_queue[largest].process_name,
process_queue[largest].arrival_time, process_queue[largest].burst_time,
process_queue[largest].priority, process_queue[largest].waiting_time);
}
average_waiting_time = wait_time / limit;
average_turnaround_time = turnaround_time / limit;
printf("\n\nAverage waiting time:\t%f\n", average_waiting_time);
printf("Average Turnaround Time:\t%f\n", average_turnaround_time);
}
OUTPUT:
Assignment 3-Implement FIFO Page Replacement Algorithm and
calculate number of page fault. Reference Strings: 1, 3, 0, 3, 5, 6,
3 Frame Size: 3
PROGRAM:

#include<stdio.h>

int main()
{
int reference_string[10], page_faults = 0, m, n, s, pages, frames;
printf("\nEnter Total Number of Pages:\t");
scanf("%d", &pages);
printf("\nEnter values of Reference String:\n");
for(m = 0; m < pages; m++)
{
printf("Value No. [%d]:\t", m + 1);
scanf("%d", &reference_string[m]);
}
printf("\nEnter Total Number of Frames:\t");
{
scanf("%d", &frames);
}
int temp[frames];
for(m = 0; m < frames; m++)
{
temp[m] = -1;
}
for(m = 0; m < pages; m++)
{
s = 0;
for(n = 0; n < frames; n++)
{
if(reference_string[m] == temp[n])
{
s++;
page_faults--;
}
}
page_faults++;
if((page_faults <= frames) && (s == 0))
{
temp[m] = reference_string[m];
}
else if(s == 0)
{
temp[(page_faults - 1) % frames] = reference_string[m];
}
printf("\n");
for(n = 0; n < frames; n++)
{
printf("%d\t", temp[n]);
}
}
printf("\nTotal Page Faults:\t%d\n", page_faults);
return 0;
}

OUTPUT:
Assignment 3b-Implement LRU Page Replacement Algorithm and
calculate the number of page fault. Reference Strings: 1, 2, 3, 4,
1, 2, 5, 1, 2, 3, 4, 5 Frame Size: 4

PROGRAM:

#include<stdio.h>

int main()

{
int frames[10], temp[10], pages[10];
int total_pages, m, n, position, k, l, total_frames;
int a = 0, b = 0, page_fault = 0;
printf("\nEnter Total Number of Frames:\t");
scanf("%d", &total_frames);
for(m = 0; m < total_frames; m++)
{
frames[m] = -1;
}
printf("Enter Total Number of Pages:\t");
scanf("%d", &total_pages);
printf("Enter Values for Reference String:\n");
for(m = 0; m < total_pages; m++)
{
printf("Value No.[%d]:\t", m + 1);
scanf("%d", &pages[m]);
}
for(n = 0; n < total_pages; n++)
{
a = 0, b = 0;
for(m = 0; m < total_frames; m++)
{
if(frames[m] == pages[n])
{
a = 1;
b = 1;
break;
}
}
if(a == 0)
{
for(m = 0; m < total_frames; m++)
{
if(frames[m] == -1)
{
frames[m] = pages[n];
b = 1;
break;
}
}
}
if(b == 0)
{
for(m = 0; m < total_frames; m++)
{
temp[m] = 0;
}
for(k = n - 1, l = 1; l <= total_frames - 1; l++, k--)
{
for(m = 0; m < total_frames; m++)
{
if(frames[m] == pages[k])
{
temp[m] = 1;
}
}
}
for(m = 0; m < total_frames; m++)
{
if(temp[m] == 0)
position = m;
}
frames[position] = pages[n];
page_fault++;
}
printf("\n");
for(m = 0; m < total_frames; m++)
{
printf("%d\t", frames[m]);
}
}
printf("\nTotal Number of Page Faults:\t%d\n", page_fault);
return 0;
}

OUTPUT:
Assignment 3c-Implement Optimal Page Replacement Algorithm
and calculate the number of page fault. Reference Strings: 2, 3, 4,
2, 1, 3, 7, 5, 4, 3 Frame Size: 3

Assignment 4-Write the Semaphore code to solve Reader-Writer


Problem
PROGRAM:

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

void *reader(void *);


void *writer(void *);

int readcount=0,writecount=0,sh_var=5,bsize[5];
sem_t x,y,z,rsem,wsem;
pthread_t r[3],w[2];

void *reader(void *i)


{
cout << "\n-------------------------";
cout << "\n\n reader-" << i << " is reading";

sem_wait(&z);
sem_wait(&rsem);
sem_wait(&x);
readcount++;
if(readcount==1)
sem_wait(&wsem);
sem_post(&x);
sem_post(&rsem);
sem_post(&z);
cout << "\nupdated value :" << sh_var;
sem_wait(&x);
readcount--;
if(readcount==0)
sem_post(&wsem);
sem_post(&x);
}
void *writer(void *i)
{
cout << "\n\n writer-" << i << "is writing";
sem_wait(&y);
writecount++;
if(writecount==1)
sem_wait(&rsem);
sem_post(&y);
sem_wait(&wsem);

sh_var=sh_var+5;
sem_post(&wsem);
sem_wait(&y);
writecount--;
if(writecount==0)
sem_post(&rsem);
sem_post(&y);
}

int main()
{
sem_init(&x,0,1);
sem_init(&wsem,0,1);
sem_init(&y,0,1);
sem_init(&z,0,1);
sem_init(&rsem,0,1);

pthread_create(&r[0],NULL,(void *)reader,(void *)0);


pthread_create(&w[0],NULL,(void *)writer,(void *)0);
pthread_create(&r[1],NULL,(void *)reader,(void *)1);
pthread_create(&r[2],NULL,(void *)reader,(void *)2);
pthread_create(&r[3],NULL,(void *)reader,(void *)3);
pthread_create(&w[1],NULL,(void *)writer,(void *)3);
pthread_create(&r[4],NULL,(void *)reader,(void *)4);

pthread_join(r[0],NULL);
pthread_join(w[0],NULL);
pthread_join(r[1],NULL);
pthread_join(r[2],NULL);
pthread_join(r[3],NULL);
pthread_join(w[1],NULL);
pthread_join(r[4],NULL);

return(0);
}
OUTPUT:
Assignment 5-Write a Semaphore code to solve Dining
philosopher problem in OS

PROGRAM:

#include<stdio.h>

#define n 4

int compltedPhilo = 0,i;

struct fork{
int taken;
}ForkAvil[n];

struct philosp{
int left;
int right;
}Philostatus[n];

void goForDinner(int philID){ //same like threads concept here cases implemented
if(Philostatus[philID].left==10 && Philostatus[philID].right==10)
printf("Philosopher %d completed his dinner\n",philID+1);
//if already completed dinner
else if(Philostatus[philID].left==1 && Philostatus[philID].right==1){
//if just taken two forks
printf("Philosopher %d completed his dinner\n",philID+1);

Philostatus[philID].left = Philostatus[philID].right = 10; //remembering that he


completed dinner by assigning value 10
int otherFork = philID-1;

if(otherFork== -1)
otherFork=(n-1);

ForkAvil[philID].taken = ForkAvil[otherFork].taken = 0; //releasing forks


printf("Philosopher %d released fork %d and fork
%d\n",philID+1,philID+1,otherFork+1);
compltedPhilo++;
}
else if(Philostatus[philID].left==1 && Philostatus[philID].right==0){ //left already
taken, trying for right fork
if(philID==(n-1)){
if(ForkAvil[philID].taken==0){ //KEY POINT OF THIS PROBLEM, THAT
LAST PHILOSOPHER TRYING IN reverse DIRECTION
ForkAvil[philID].taken = Philostatus[philID].right = 1;
printf("Fork %d taken by philosopher %d\n",philID+1,philID+1);
}else{
printf("Philosopher %d is waiting for fork %d\n",philID+1,philID+1);
}
}else{ //except last philosopher case
int dupphilID = philID;
philID-=1;

if(philID== -1)
philID=(n-1);

if(ForkAvil[philID].taken == 0){
ForkAvil[philID].taken = Philostatus[dupphilID].right = 1;
printf("Fork %d taken by Philosopher %d\n",philID+1,dupphilID+1);
}else{
printf("Philosopher %d is waiting for Fork %d\n",dupphilID+1,philID+1);
}
}
}
else if(Philostatus[philID].left==0){ //nothing taken yet
if(philID==(n-1)){
if(ForkAvil[philID-1].taken==0){ //KEY POINT OF THIS PROBLEM, THAT
LAST PHILOSOPHER TRYING IN reverse DIRECTION
ForkAvil[philID-1].taken = Philostatus[philID].left = 1;
printf("Fork %d taken by philosopher %d\n",philID,philID+1);
}else{
printf("Philosopher %d is waiting for fork %d\n",philID+1,philID);
}
}else{ //except last philosopher case
if(ForkAvil[philID].taken == 0){
ForkAvil[philID].taken = Philostatus[philID].left = 1;
printf("Fork %d taken by Philosopher %d\n",philID+1,philID+1);
}else{
printf("Philosopher %d is waiting for Fork %d\n",philID+1,philID+1);
}
}
}else{}
}

int main(){
for(i=0;i<n;i++)
ForkAvil[i].taken=Philostatus[i].left=Philostatus[i].right=0;

while(compltedPhilo<n){
/* Observe here carefully, while loop will run until all philosophers
complete dinner
Actually problem of deadlock occur only thy try to take at same time
This for loop will say that they are trying at same time. And remaining
status will print by go for dinner function
*/
for(i=0;i<n;i++)
goForDinner(i);
printf("\nTill now num of philosophers completed dinner are
%d\n\n",compltedPhilo);
}

return 0;
}

OUTPUT:
Assignment 6-Write code for Banker's Algorithm and test whether
system can avoid deadlock or not​.

#include<iostream>

using namespace std;

// Number of processes

const int P = 5;

// Number of resources

const int R = 3;

// Function to find the need of each process

void calculateNeed(int need[P][R], int maxm[P][R],

int allot[P][R])

// Calculating Need of each P

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

for (int j = 0 ; j < R ; j++)

// Need of instance = maxm instance -

// allocated instance

need[i][j] = maxm[i][j] - allot[i][j];

}
// Function to find the system is in safe state or not

bool isSafe(int processes[], int avail[], int maxm[][R],

int allot[][R])

int need[P][R];

// Function to calculate need matrix

calculateNeed(need, maxm, allot);

// Mark all processes as infinish

bool finish[P] = {0};

// To store safe sequence

int safeSeq[P];

// Make a copy of available resources

int work[R];

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

work[i] = avail[i];

// While all processes are not finished

// or system is not in safe state.

int count = 0;
while (count < P)

// Find a process which is not finish and

// whose needs can be satisfied with current

// work[] resources.

bool found = false;

for (int p = 0; p < P; p++)

// First check if a process is finished,

// if no, go for next condition

if (finish[p] == 0)

// Check if for all resources of

// current P need is less

// than work

int j;

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

if (need[p][j] > work[j])

break;

// If all needs of p were satisfied.

if (j == R)

// Add the allocated resources of


// current P to the available/work

// resources i.e.free the resources

for (int k = 0 ; k < R ; k++)

work[k] += allot[p][k];

// Add this process to safe sequence.

safeSeq[count++] = p;

// Mark this p as finished

finish[p] = 1;

found = true;

// If we could not find a next process in safe

// sequence.

if (found == false)

cout << "System is not in safe state";

return false;

}
// If system is in safe state then

// safe sequence will be as below

cout << "System is in safe state.\nSafe"

" sequence is: ";

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

cout << safeSeq[i] << " ";

return true;

// Driver code

int main()

int processes[] = {0, 1, 2, 3, 4};

// Available instances of resources

int avail[] = {3, 3, 2};

// Maximum R that can be allocated

// to processes

int maxm[][R] = {{7, 5, 3},

{3, 2, 2},

{9, 0, 2},
{2, 2, 2},

{4, 3, 3}};

// Resources allocated to processes

int allot[][R] = {{0, 1, 0},

{2, 0, 0},

{3, 0, 2},

{2, 1, 1},

{0, 0, 2}};

// Check system is in safe state or not

isSafe(processes, avail, maxm, allot);

return 0;

OUTPUT:

You might also like