fork download
  1. #include<stdio.h>
  2. int main()
  3. {
  4. int i,j,k,p,r,flag=1,c,c1=0;
  5. int alloc[10][10],max[10][10],avail[10],need[10][10],finish[10];
  6. printf("\nEnter the number of processes");
  7. scanf("%d",&p);
  8. printf("\nEnter the number of resources");
  9. scanf("%d",&r);
  10. printf("\nEnter the allocation matrix");
  11. for(i=0;i<p;i++)
  12. {
  13. for(j=0;j<r;j++)
  14. {
  15. scanf("%d",&alloc[i][j]);
  16.  
  17. }
  18. }
  19. printf("\nEnter the max matrix");
  20. for(i=0;i<p;i++)
  21. {
  22. for(j=0;j<r;j++)
  23. {
  24. scanf("%d",&max[i][j]);
  25. }
  26. }
  27. printf("\nEnter the available matrix");
  28. for(i=0;i<r;i++)
  29. {
  30. scanf("%d",&avail[i]);
  31. }
  32. printf("\nthe need matrix is:");
  33. for(i=0;i<p;i++)
  34. {
  35. printf("\n");
  36. for(j=0;j<r;j++)
  37. {
  38. need[i][j]=max[i][j]-alloc[i][j];
  39. printf("%d ",need[i][j]);
  40. }
  41. }
  42. for(i=0;i<p;i++)
  43. {
  44. finish[i]=0;
  45. }
  46. while(flag)
  47. {
  48. flag=0;
  49. for(i=0;i<p;i++)
  50. {
  51. c=0;
  52. for(j=0;j<r;j++)
  53. {
  54. if(finish[i]==0 && need[i][j]<=avail[j])
  55. {
  56. c++;
  57. if(c==r)
  58. {
  59. for(k=0;k<r;k++)
  60. {
  61. avail[k]=avail[k]+alloc[i][k];
  62. }
  63. flag=1;
  64. finish[i]=1;
  65. printf("P%d->",i);
  66. i=p;
  67. }
  68. }
  69. }
  70. }
  71. }
  72. for(i=0;i<p;i++)
  73. {
  74. if(finish[i]==1)
  75. {
  76. c1++;
  77. }
  78. else
  79. {
  80. printf("P%d->",i);
  81. }
  82. }
  83. if(c1==p)
  84. {
  85. printf("\nsystem is in safe state");
  86. }
  87. else
  88. {
  89. printf("\nsystem is not in safe state");
  90. }
  91. return 0;
  92.  
  93.  
  94.  
  95. }
Success #stdin #stdout 0s 5432KB
stdin
5
4
0 0 1 2
1 0 0 0
1 3 5 4
0 6 3 2
0 0 1 4
0 0 1 2
1 7 5 0
2 3 5 6
0 6 5 2
0 6 5 6
1 5 2 0
stdout
Enter the number of processes
Enter the number of resources
Enter the allocation matrix
Enter the max matrix
Enter the available matrix
the need matrix is:
0 0 0 0 
0 7 5 0 
1 0 0 2 
0 0 2 0 
0 6 4 2 P0->P2->P1->P3->P4->
system is in safe state