-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path7_bankersAlgorithm.c
90 lines (88 loc) · 2.88 KB
/
7_bankersAlgorithm.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
7. Write a C program to simulate Bankers algorithm for the purpose of deadlock avoidance.
*/
#include <stdio.h>
#include <stdlib.h>
int main() {
int Max[10][10], need[10][10], alloc[10][10], availableResources[10], completed[10], safeSequence[10];
int numProcesses, numResources, i, j, process, count;
count = 0;
printf("Enter the number of processes: ");
scanf("%d", &numProcesses);
for(i = 0; i < numProcesses; i++) {
completed[i] = 0;
}
printf("\n\nEnter the number of resources: ");
scanf("%d", &numResources);
printf("\n\nEnter the Max Matrix for each process:");
for(i = 0; i < numProcesses; i++) {
printf("\nFor process %d: ", i + 1);
for(j = 0; j < numResources; j++) {
scanf("%d", &Max[i][j]);
}
}
printf("\n\nEnter the allocation for each process: ");
for(i = 0; i < numProcesses; i++) {
printf("\nFor process %d: ",i + 1);
for(j = 0; j < numResources; j++) {
scanf("%d", &alloc[i][j]);
}
}
printf("\n\nEnter the Available Resources: ");
for(i = 0; i < numResources; i++) {
scanf("%d", &availableResources[i]);
}
for(i = 0; i < numProcesses; i++) {
for(j = 0; j < numResources; j++) {
need[i][j] = Max[i][j] - alloc[i][j];
}
}
do {
printf("\n Max matrix:\tAllocation matrix:\n");
for(i = 0; i < numProcesses; i++) {
for(j = 0; j < numResources; j++) {
printf("%d ", Max[i][j]);
}
printf("\t\t");
for(j = 0; j < numResources; j++) {
printf("%d ", alloc[i][j]);
}
printf("\n");
}
process = -1;
for(i = 0; i < numProcesses; i++) {
if(completed[i] == 0) { //if not completed
process = i;
for(j = 0; j < numResources; j++) {
if(availableResources[j] < need[i][j]) {
process = -1;
break;
}
}
}
if(process != -1)
break;
}
if(process != -1) {
printf("\nProcess %d runs to completion!", process + 1);
safeSequence[count] = process + 1; count++;
for(j = 0; j < numResources; j++) {
availableResources[j] += alloc[process][j];
alloc[process][j] = 0;
Max[process][j] = 0;
completed[process] = 1;
}
}
}
while(count != numProcesses && process != -1);
if(count == numProcesses) {
printf("\nThe system is in a safe state!!\n");
printf("Safe Sequence: < ");
for( i = 0; i < numProcesses; i++) {
printf("%d ", safeSequence[i]);
}
printf(">\n");
}
else
printf("\nThe system is in an unsafe state!!");
}