8 Os
8 Os
PROGRAM:
#include <stdio.h>
#define MAX 10
void detectDeadlock(int allocation[MAX][MAX], int max[MAX][MAX], int
available[MAX], int n, int m) {
int finish[MAX] = {0};
int work[MAX];
for (int i = 0; i < m; i++) {
work[i] = available[i];
}
int safeSequence[MAX];
int safeCount = 0;
int processCompleted;
while (safeCount < n) {
processCompleted = 0;
for (int i = 0; i < n; i++) {
if (!finish[i]) {
int canExecute = 1;
for (int j = 0; j < m; j++) {
if (max[i][j] - allocation[i][j] > work[j]) {
canExecute = 0;
break;
}}
if (canExecute) {
for (int j = 0; j < m; j++) {
work[j] += allocation[i][j];
}
safeSequence[safeCount++] = i;
finish[i] = 1;
processCompleted = 1;
break;
}}
}if (!processCompleted) {
printf("\nDeadlock detected: No safe sequence found.\n");
return;
}}
printf("\nSafe Sequence: ");
for (int i = 0; i < safeCount; i++) {
printf("P%d ", safeSequence[i] + 1);
}
printf("\n");
}
int main() {
int allocation[MAX][MAX], max[MAX][MAX], available[MAX];
int n, m;
printf("\nEnter the number of processes: ");
scanf("%d", &n);
printf("\nEnter the number of resource types: ");
scanf("%d", &m);
printf("\nEnter the allocation matrix:\n");
for (int i = 0; i < n; i++) {
printf("For process P%d, enter allocated resources: ", i + 1);
for (int j = 0; j < m; j++) {
scanf("%d", &allocation[i][j]);
}}
printf("\nEnter the maximum resource matrix:\n");
for (int i = 0; i < n; i++) {
printf("For process P%d, enter maximum resources: ", i + 1);
for (int j = 0; j < m; j++) {
scanf("%d", &max[i][j]);
}}
printf("\nEnter the available resources: ");
for (int i = 0; i < m; i++) {
scanf("%d", &available[i]);
}
detectDeadlock(allocation, max, available, n, m);
return 0;
}
OUTPUT:
Enter the number of processes: 5
Enter the number of resource types: 3
Enter the allocation matrix:
For process P1, enter allocated resources: 0 1 0
For process P2, enter allocated resources: 2 0 0
For process P3, enter allocated resources: 3 0 2
For process P4, enter allocated resources: 2 1 1
For process P5, enter allocated resources: 0 0 2
Safe Sequence: P1 P3 P5 P4 P2