Banker's Algorithm in C
Aim
To implement the Banker’s Algorithm in C for deadlock avoidance and determine whether the system is in a safe state or unsafe state.
Introduction
The Banker’s Algorithm is a deadlock avoidance algorithm used in Operating Systems.
It checks whether resources can be safely allocated to processes without causing a deadlock.
The algorithm works by:
- Calculating the Need Matrix
- Checking available resources
- Finding a Safe Sequence
If all processes can execute successfully, the system is in a Safe State.
#include <stdio.h>
#define MAX_PROCESSES 10
#define MAX_RESOURCES 10
int available[MAX_RESOURCES];
int max[MAX_PROCESSES][MAX_RESOURCES];
int allocation[MAX_PROCESSES][MAX_RESOURCES];
int need[MAX_PROCESSES][MAX_RESOURCES];
int main()
{
int num_processes, num_resources;
printf("Enter the number of processes: ");
scanf("%d", &num_processes);
printf("Enter the number of resources: ");
scanf("%d", &num_resources);
// Input Available Resources
printf("Enter the available resources:\n");
for (int i = 0; i < num_resources; i++)
{
scanf("%d", &available[i]);
}
// Input Maximum Requirement Matrix
printf("Enter maximum resources for each process:\n");
for (int i = 0; i < num_processes; i++)
{
printf("Process %d: ", i);
for (int j = 0; j < num_resources; j++)
{
scanf("%d", &max[i][j]);
}
}
// Input Allocation Matrix
printf("Enter allocated resources for each process:\n");
for (int i = 0; i < num_processes; i++)
{
printf("Process %d: ", i);
for (int j = 0; j < num_resources; j++)
{
scanf("%d", &allocation[i][j]);
// Calculate Need Matrix
need[i][j] = max[i][j] - allocation[i][j];
}
}
int finish[MAX_PROCESSES] = {0};
int safeSequence[MAX_PROCESSES];
int work[MAX_RESOURCES];
// Copy available resources into work array
for (int i = 0; i < num_resources; i++)
{
work[i] = available[i];
}
int count = 0;
// Banker's Algorithm
while (count < num_processes)
{
int found = 0;
for (int i = 0; i < num_processes; i++)
{
if (finish[i] == 0)
{
int j;
// Check if process can execute
for (j = 0; j < num_resources; j++)
{
if (need[i][j] > work[j])
{
break;
}
}
// If all resources are available
if (j == num_resources)
{
// Release allocated resources
for (int k = 0; k < num_resources; k++)
{
work[k] += allocation[i][k];
}
safeSequence[count] = i;
finish[i] = 1;
printf("Process %d completed\n", i);
count++;
found = 1;
}
}
}
// Unsafe State
if (!found)
{
printf("\nSystem is in Unsafe State!\n");
return 0;
}
}
// Safe State
printf("\nSystem is in Safe State.\n");
printf("Safe Sequence: ");
for (int i = 0; i < num_processes; i++)
{
printf("P%d ", safeSequence[i]);
}
printf("\n");
return 0;
}

useless code rejected
ReplyDelete