safe


#include<stdio.h>
#include<stdlib.h>

int n,m,pno;
int max[10][10],alloc[10][10],need[10][10],avail[10],req[10],work[10],safe[10];

void accept();
void safety_algo();
void cal_need();
void display();
int compare_need(int);

int main()
{

int ch;
printf("Enter how many process do you wants\n");
scanf("%d",&n);

printf("Enter how many resources do you wants\n");
scanf("%d",&m);
accept();
cal_need;
display();
safety_algo();
}

void accept()
{
int i,j;
printf("Enter the elemets of the max matrix\n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("enter the element for max[%d][%d] location\n",(i+1),(j+1));
scanf("%d",&max[i][j]);
}
}
printf("Enter the elements of the allocation matrix\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("Enter the eleements of alloc[%d][%d] location\n",(i+1),(j+1));
scanf("%d",&alloc[i][j]);
}
}
printf("Enter the elements of the available\n");
for(i=0;i<m;i++)
{
printf("Enter the available resource of the %d resource\n",i);
scanf("%d",&avail[i]);
}

}
void cal_need()
{
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
need[i][j]=max[i][j]-alloc[i][j];
}
}

}
void display()
{
int i,j;
printf("max matrix is: \n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%d\t",max[i][j]);
}
printf("\n");
}
printf("Alloated matrix is: \n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%d\t",alloc[i][j]);
}
printf("\n");
}
printf("Need matrix is: \n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%d\t",need[i][j]);
}
printf("\n");
}
printf("Available matrix is:\n");
for(i=0;i<m;i++)
{
printf("%d\t",avail[i]);
}
}

int compare_need(int p)
{
int i,j,flag=0;
for(j=0;j<m;j++)
{
if(need[p][j]>work[j])
{
flag=1;
break;
}
}
if(flag==0)
return p;
return -1;
}

void safety_algo()
{
int finish[10]={0};
int over=0,i,j,k,l=0,flag;
for(i=0;i<m;i++)
{
work[i]=avail[i];
}
while(!over)
{
for(i=0;i<n;i++)
{
if(finish[i]==0)
{
flag=0;
pno=compare_need(i);
if(pno > -1)
break;
}
}
if(i==n)
{
printf("system is in the unsafe state\n");
exit(1);
}
if(i<n && pno>=0)
{
for(k=0;k<m;k++)
work[k]+=alloc[pno][k];
finish[pno]=1;
safe[l++]=pno;
if(l>=n)
{
printf("system is in the safe state\n");
printf("safe sequence is \n");
for(l=0;l<n;l++)
{
printf("P%d\t",safe[l]);
}
over=1;
}
}
}

}