#include <stdio.h>
#define P 5
#define R 3
int main() {
int i, j, k;
int alloc[P][R] = { {0, 1, 0}, {2, 0, 0}, {3, 0, 2}, {2, 1, 1}, {0, 0, 2} };
int max[P][R] = { {7, 5, 3}, {3, 2, 2}, {9, 0, 2}, {2, 2, 2}, {4, 3, 3} };
int avail[R] = {3, 3, 2};
int f[P], ans[P], ind = 0;
for (k = 0; k < P; k++)
f[k] = 0;
int need[P][R];
for (i = 0; i < P; i++)
for (j = 0; j < R; j++)
need[i][j] = max[i][j] - alloc[i][j];
int y = 0;
for (k = 0; k < P; k++) {
for (i = 0; i < P; i++) {
if (f[i] == 0) {
int flag = 0;
for (j = 0; j < R; j++) {
if (need[i][j] > avail[j]) {
flag = 1;
break;
}
}
if (flag == 0) {
ans[ind++] = i;
for (y = 0; y < R; y++)
avail[y] += alloc[i][y];
f[i] = 1;
}
}
}
}
int flag = 1;
for (i = 0; i < P; i++)
if (f[i] == 0) {
flag = 0;
break;
}
if (flag == 1) {
printf("System is in a safe state.\nSafe sequence is: ");
for (i = 0; i < P - 1; i++)
printf("P%d -> ", ans[i]);
printf("P%d\n", ans[P - 1]);
} else {
printf("System is not in a safe state.\n");
}
return 0;
}
This code assumes 5 processes and 3 resource types. You can modify the number of processes and resources by changing the P and R variables. The matrix alloc represents the allocated resources, max represents the maximum demand of each process, and avail is the available resources. The algorithm calculates the need matrix and attempts to find a safe sequence where all processes can be executed without leading to a deadlock.