fork download
  1.  
  2. #include <stdio.h>
  3.  
  4. int main() {
  5. int n, m, i, j, k;
  6.  
  7.  
  8. printf("Enter number of processes: ");
  9. scanf("%d", &n);
  10.  
  11. printf("Enter number of resource types: ");
  12. scanf("%d", &m);
  13.  
  14. int alloc[n][m], max[n][m], need[n][m];
  15. int avail[m], finish[n], safe[n];
  16.  
  17.  
  18. printf("\nEnter Allocation Matrix:\n");
  19. for(i = 0; i < n; i++) {
  20. for(j = 0; j < m; j++) {
  21. scanf("%d", &alloc[i][j]);
  22. }
  23. }
  24.  
  25. printf("\nEnter Max Matrix:\n");
  26. for(i = 0; i < n; i++) {
  27. for(j = 0; j < m; j++) {
  28. scanf("%d", &max[i][j]);
  29. }
  30. }
  31.  
  32.  
  33. printf("\nEnter Available Resources:\n");
  34. for(j = 0; j < m; j++) {
  35. scanf("%d", &avail[j]);
  36. }
  37.  
  38.  
  39. for(i = 0; i < n; i++) {
  40. for(j = 0; j < m; j++) {
  41. need[i][j] = max[i][j] - alloc[i][j];
  42. }
  43. finish[i] = 0;
  44. }
  45.  
  46.  
  47. int count = 0;
  48. while(count < n) {
  49. int found = 0;
  50. for(i = 0; i < n; i++) {
  51. if(finish[i] == 0) {
  52. for(j = 0; j < m; j++) {
  53. if(need[i][j] > avail[j])
  54. break;
  55. }
  56.  
  57. if(j == m) {
  58. for(k = 0; k < m; k++)
  59. avail[k] += alloc[i][k];
  60.  
  61. safe[count++] = i;
  62. finish[i] = 1;
  63. found = 1;
  64. }
  65. }
  66. }
  67.  
  68. if(found == 0) {
  69. printf("\nSystem is NOT in safe state.\n");
  70. return 0;
  71. }
  72. }
  73.  
  74.  
  75. printf("\nSystem is in SAFE state.\nSafe sequence is:\n");
  76. for(i = 0; i < n; i++) {
  77. printf("P%d ", safe[i]);
  78. }
  79.  
  80. return 0;
  81. }
Success #stdin #stdout 0.01s 5272KB
stdin
Standard input is empty
stdout
Enter number of processes: Enter number of resource types: 
Enter Allocation Matrix:

Enter Max Matrix:

Enter Available Resources:

System is in SAFE state.
Safe sequence is: