#include <stdio.h>
int main() {
int n, m, i, j, k;
n = 5; // Number of processes
m = 3; // Number of resources
int alloc[5][3] = {{0, 1, 0}, // Allocation Matrix
{2, 0, 0},
{3, 0, 2},
{2, 1, 1},
{0, 0, 2}};
int max[5][3] = {{7, 5, 3}, // MAX Matrix
{3, 2, 2},
{9, 0, 2},
{2, 2, 2},
{4, 3, 3}};
int avail[3] = {3, 3, 2}; // Available Resources
int f[n], ans[n], ind = 0;
for (k = 0; k < n; k++) {
f[k] = 0; // Initialize all processes as unfinished
}
int need[n][m];
// Calculate Need Matrix
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++)
need[i][j] = max[i][j] - alloc[i][j];
}
// Safety Algorithm
int y = 0;
for (k = 0; k < 5; k++) { // Repeat until all processes are checked
for (i = 0; i < n; i++) { // Loop through each process
if (f[i] == 0) { // Check if the process is not finished
int flag = 0;
for (j = 0; j < m; j++) {
// Check if all resource needs of the process can be satisfied with available resources
if (need[i][j] > avail[j]) {
flag = 1; // If any resource need exceeds available resources, set flag to 1
break;
}
}
if (flag == 0) { // If all resource needs can be satisfied
ans[ind++] = i; // Add process to safe sequence
// Update available resources by adding allocated resources of the process
for (y = 0; y < m; y++)
avail[y] += alloc[i][y];
f[i] = 1; // Mark process as finished
}
}
}
}
// Safety Check
int flag = 1;
for (int i = 0; i < n; i++) {
if (f[i] == 0) { // If any process is not finished
flag = 0; // Set flag to 0 indicating system is not in a safe state
printf("The following system is not safe");
break;
}
}
// Output
if (flag == 1) { // If system is in a safe state
printf("Following is the SAFE Sequence\n");
for (i = 0; i < n - 1; i++)
printf(" P%d ->", ans[i]);
printf(" P%d", ans[n - 1]);
}
return (0);
}