Name : Prabhakar Uparkar
Roll No : 58
Assignment 7
Q. Write a C Program to implement Bankers Algorithm.
#include <stdio.h>
int processExecuted(int PSequence[], int i, int P) {
for (int j = 0; j < P; j++) {
if (PSequence[j] == i) {
return 1;
}
}
return 0;
}
int main() {
int P, R;
printf("Enter the number of processes: ");
scanf("%d", &P);
printf("Enter the number of resources: ");
scanf("%d", &R);
// Allocation
int alloc[P][R];
for (int i = 0; i < P; i++) {
printf("Enter allocation of Process %d: ", i);
for (int j = 0; j < R; j++) {
scanf("%d", &alloc[i][j]);
}
}
// MAX
int MAX[P][R];
for (int i = 0; i < P; i++) {
printf("Enter MAX of Process %d: ", i);
for (int j = 0; j < R; j++) {
scanf("%d", &MAX[i][j]);
}
}
// Available
int available[R];
printf("Enter available resources: ");
for (int i = 0; i < R; i++) {
scanf("%d", &available[i]);
}
// NEED matrix calculation
int need[P][R];
for (int i = 0; i < P; i++) {
for (int j = 0; j < R; j++) {
need[i][j] = MAX[i][j] - alloc[i][j];
}
}
// The process sequence that should be executed
int PSequence[P];
for (int i = 0; i < P; i++) {
PSequence[i] = -1;
}
int finishedProcesses = 0;
int k = 0;
int foundProcess;
while (finishedProcesses < P) {
foundProcess = 0;
for (int i = 0; i < P; i++) {
if (processExecuted(PSequence, i, P) == 0) {
int canExecute = 1;
for (int j = 0; j < R; j++) {
if (need[i][j] > available[j]) {
canExecute = 0;
break;
}
}
if (canExecute) {
for (int j = 0; j < R; j++) {
available[j] += alloc[i][j];
}
PSequence[k++] = i;
finishedProcesses++;
foundProcess = 1;
printf("Process %d has been executed.\n", i);
}
}
}
if (!foundProcess) {
printf("System is in an unsafe state. No safe sequence
found.\n");
return 1;
}
}
printf("System is in a safe state.\nSafe sequence is: ");
for (int i = 0; i < P; i++) {
printf("P%d ", PSequence[i]);
}
printf("\n");
return 0;
}
Output: