Sjf

PHOTO EMBED

Sat Mar 22 2025 07:59:37 GMT+0000 (Coordinated Universal Time)

Saved by @ccc

#include<stdio.h>
int main()
{
int max[10][10],need[10][10],alloc[10][10],avail[10],work[10];
int p,r,i,j,process,flag,executed=0,canExecute;
char finish[10];
printf("\nEnter the no. of processes and resources:");
scanf("%d%d",&p,&r);

 //Input Max matrix
printf("\nEnter the Max Matrix for each process:");
for(i=0;i<p;i++)
{
for(j=0;j<r;j++)
scanf("%d",&max[i][j]);
}
// Input Allocation Matrix
printf("\nEnter the allocation for each process:");
for(i=0;i<p;i++)
{
for(j=0;j<r;j++)
scanf("%d",&alloc[i][j]);
}
// Input Available Resources after allocation
printf("\n\n Enter the Available Resources:");
for(i=0;i<r;i++)
scanf("%d",&avail[i]);
// Calculation of Need Matrix
for(i=0;i<p;i++)
{
printf("\n");
for(j=0;j<r;j++)
{
need[i][j]=max[i][j]-alloc[i][j];
printf("%d",need[i][j]);
}
printf("\t\t");
}
for(i=0;i<p;i++)
finish[i]='F';
for(j=0;j<r;j++)
work[j]=avail[j];
printf("\nSafe Sequence: ");
   while (executed < p) {
       flag = 0;
 
       for (i = 0; i < p; i++) {
           if (finish[i] == 'F') {
                canExecute = 1;
               
               // Check if need can be satisfied
               for (j = 0; j < r; j++) {
                   if (need[i][j] > work[j]) {
                       canExecute = 0;
                       break;
                   }
               }
 
               if (canExecute) {
                   // Process can execute
                   printf("P%d ", i);
                   for (j = 0; j < r; j++)
                       work[j] += alloc[i][j];
 
                   finish[i] = 'T';
                   executed++;
                   flag = 1;
               }
           }
       }
 
       // If no process is executed in an iteration, break (unsafe state)
       if (flag == 0) {
           printf("\nSystem is in an unsafe state!");
           return 1;
       }
   }
 
   printf("\nSystem is in a safe state.");
   return 0;
}
content_copyCOPY