#include<stdio.h>
#include<stdlib.h>
static int available[3]={3,3,2};
static int allocation[5][3]={{0,1,0},{2,0,0},{3,0,2},{2,1,1,},{0,0,2}};
static int need[5][3]={{7,4,3},{1,2,2},{6,0,0},{0,1,1},{4,3,1}};
int work[3], finish[4],state;
int safe()
{
int i,j=0;
for(i=0;i<4;i++)
if(finish[i]==1)
j++;
if(j==4)
return 1;
return 0;
}
void show()
{
if(safe())
{
state=1;
printf("system is in safe state/n");
}
else
{
state=0;
printf("system is not in safe state/n");
}
}
void reallocation(int k)
{
int j,i=k;
for(j=0;j<3;j++)
work[j]+=allocation[i][j];
finish[i]=1;
}
int check(int k)
{
int j,i=k,l=0;
if(finish[i]==0)
{
for(j=0;j<3;j++)
if(need[i][j]<=work[j])
l++;
}
if(l==3)
return 1;
return 0;
}
int find()
{
int i,j=0;
for(i=0;i<4;i++)
{
if(check(i))
break;
else
j++;
}
if(j==4)
return -1;
return i;
}
void safestatecheck()
{
while(!safe())
{
if(find()!=-1)
reallocation(find());
else
break;
}
show();
}
main()
{
int i,id,k=0,request[5][3];
for(i=0;i<3;i++)
work[i]=available[i];
for(i=0;i<4;i++)
finish[i]=0;
safestatecheck();
while(1)
{
printf("switch the id of process,please/n");
scanf("%d",&id);
if(id<5)
break;
else printf("error,");
}
for(i=0;i<3;i++)
{
printf("input the number of resourse%d/n",i);
scanf("%d",&request[id][i]);
}
for(i=0;i<3;i++)
if(request[id][i]<=need[id][i])
k++;
if(k<3)
{
printf("system can't accept the request/n");
exit(1);
}
else
{ k=0;
for(i=0;i<3;i++)
if(request[id][i]<=available[i])
k++;
if(k<3)
{
printf("process must wait/n");
exit(1);
}
else
{
for(i=0;i<3;i++)
{
available[i]-=request[id][i];
allocation[id][i]+=request[id][i];
need[id][i]-=request[id][i];
}
}
}
for(i=0;i<3;i++)
work[i]=available[i];
for(i=0;i<4;i++)
finish[i]=0;
safestatecheck();
if(!state)
{
printf("process must wait /n");
for(i=0;i<3;i++)
{
available[i]+=request[id][i];
allocation[id][i]-=request[id][i];
need[id][i]+=request[id][i];
}
}
else
printf("the allocation of the resourses is success/n");
}