Menu

Operating Systems [ Lab Programs ]


Aim:

  Write a C program to simulate Bankers Algorithm for Deadlock Avoidance and Prevention.

Solution :

PROGRAM: ( bankers_alg.c )

 
#include<stdio.h>
int main()
{
int process,resource,instance,j,i,k=0,count1=0,count2=0;
int avail[10] , max[10][10], allot[10][10],need[10][10],completed[10];
printf("Enter No. of Process: ");
scanf("%d",&process);
printf("Enter No. of Resources: ");
scanf("%d",&resource);
for(i=0;i<process;i++)
completed[i]=0;
printf("Enter No. of Available Instances: ");
for(i=0;i<resource;i++)
{
 scanf("%d",&instance);
 avail[i]=instance;
}
printf("Enter Maximum No. of instances of resources that a Process need:\n");
for(i=0;i<process;i++)
{
printf(" For P[%d]\t",i);
for(j=0;j<resource;j++)
{
 scanf("%d",&instance);
 max[i][j]=instance;
}
}
printf("Enter no. of instances already allocated to process of a resource:\n");
 for(i=0;i<process;i++)
 {
 printf(" For P[%d]\t",i);
 for(j=0;j<resource;j++)
{
 scanf("%d",&instance);
 allot[i][j]=instance;
 need[i][j]=max[i][j]-allot[i][j]; //calculating Need of each process
} }
 printf("\n Safe Sequence is:- \t");
 while(count1!=process)
 {
 count2=count1;
 for(i=0;i<process;i++)
         {
 for(j=0;j<resource;j++)
{
 if(need[i][j]<=avail[j])
 {
k++;
 }
}
if(k==resource && completed[i]==0 )
{
 printf("P[%d]\t",i);
 completed[i]=1;
 for(j=0;j<resource;j++)
 {
 avail[j]=avail[j]+allot[i][j];
 }
 count1++;
 }
k=0; }
if(count1==count2)
{
printf("\t Stop ..After this.....Deadlock \n");
break;

}
}
 return 0;
}

OUTPUT:

 
$ gcc bankers_alg.c
$ ./a.out
Enter No. of Process: 5
Enter No. of Resources: 3
Enter No. of Available Instances: 3
3
2
Enter Maximum No. of instances of resources that a Process need:
 For P[0]       7 5 3
 For P[1]       3 2 2
 For P[2]       9 0 2
 For P[3]       2 2 2
 For P[4]       4 3 3
Enter no. of instances already allocated to process of a resource:
 For P[0]       0 1 0
 For P[1]       2 0 0
 For P[2]       3 0 2
 For P[3]       2 1 1
 For P[4]       0 0 2

 Safe Sequence is:-     P[1]    P[3]    P[4]    P[0]    P[2] 




Related Content :

1. Write C programs to simulate the following CPU Scheduling algorithms
a) FCFS
b) SJF
c) RoundRobin
d) priority    View Solution


2. Write programs using the I/O system calls of UNIX/LINUX operating system (open, read, write, close,fcntl, seek, stat, opendir, readdir)    View Solution


3. Write a C program to simulate Bankers Algorithm for Deadlock Avoidance and Prevention.    View Solution


4. Write a C program to implement the Producer – Consumer problem using semaphores using UNIX/LINUX system calls.   View Solution


5. Write C programs to illustrate the following IPC mechanisms
a) Pipes
b) FIFOs
c) Message Queues
d) Shared Memory.    View Solution


6. Write C programs to simulate the following memory management techniques
a) Paging
b) Segmentation    View Solution


7. Write C programs to simulate Page replacement policies
a) FCFS
b) LRU
c) Optimal    View Solution