0% found this document useful (0 votes)
25 views

operating system lab file 2024-25

The document contains multiple C programs demonstrating various UNIX system calls, CPU scheduling algorithms, file storage allocation techniques, and contiguous memory allocation strategies. Each program includes detailed explanations of the implemented methods, sample inputs, and instructions for compilation and execution. Key topics covered include process management, file management, input/output system calls, SJF, priority scheduling, FCFS, multilevel queue scheduling, contiguous allocation, linked list allocation, and indexed allocation.

Uploaded by

Swati Gaur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

operating system lab file 2024-25

The document contains multiple C programs demonstrating various UNIX system calls, CPU scheduling algorithms, file storage allocation techniques, and contiguous memory allocation strategies. Each program includes detailed explanations of the implemented methods, sample inputs, and instructions for compilation and execution. Key topics covered include process management, file management, input/output system calls, SJF, priority scheduling, FCFS, multilevel queue scheduling, contiguous allocation, linked list allocation, and indexed allocation.

Uploaded by

Swati Gaur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Program 2

Execute various UNIX system calls for

i. Process management ,
ii. File management,
iii. Input/output System calls
iv. Solution:

Here’s a C program demonstrating various UNIX system calls related to:

 i. Process management
 ii. File management
 iii. Input/output system calls

Each section includes basic yet illustrative system calls.

✅ Full C Program: UNIX System Call Demonstration


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>

int main() {
printf("===== UNIX System Call Demonstration =====\n");

// i. PROCESS MANAGEMENT
printf("\n--- Process Management ---\n");
pid_t pid = fork(); // create a child process

if (pid < 0) {
perror("Fork failed");
exit(1);
} else if (pid == 0) {
printf("Child Process: PID = %d\n", getpid());
printf("Child says: Hello from child process!\n");
exit(0); // child exits
} else {
wait(NULL); // parent waits for child to finish
printf("Parent Process: PID = %d\n", getpid());
printf("Parent says: Child process finished.\n");
}
// ii. FILE MANAGEMENT
printf("\n--- File Management ---\n");
int fd = open("demo.txt", O_CREAT | O_WRONLY | O_TRUNC, 0644);
if (fd < 0) {
perror("File open error");
exit(1);
}

const char *text = "This is a demo file written using system calls.\n";
write(fd, text, strlen(text));
close(fd);

// iii. INPUT/OUTPUT SYSTEM CALLS


printf("\n--- Input/Output System Calls ---\n");
char buffer[100];
printf("Enter some text: ");
ssize_t bytesRead = read(STDIN_FILENO, buffer, sizeof(buffer));
buffer[bytesRead] = '\0'; // null-terminate input
printf("You entered: %s", buffer);

return 0;
}

🔧 Compile & Run the Program


gcc unix_syscalls.c -o unix_syscalls
./unix_syscalls

📌 Explanation of System Calls Used

Category System Call(s) Purpose


Process Management fork(), getpid(), wait() Create child, get PID, wait for child
File Management open(), write(), close() Create/write to file
I/O System Calls read(), STDIN_FILENO Input from user using system-level read
Program 3

Implement CPU Scheduling Policies:

i. SJF ,
ii. Priority
iii. FCFS,
iv. Multi-level Queue.

Here's a complete C program that demonstrates CPU Scheduling Algorithms:

 i. Shortest Job First (SJF)


 ii. Priority Scheduling
 iii. First-Come First-Serve (FCFS)
 iv. Multilevel Queue Scheduling

Each algorithm is implemented separately for clarity.

✅ Full C Program: CPU Scheduling Algorithms


#include <stdio.h>

#define MAX 10

typedef struct {
int pid;
int bt; // Burst Time
int at; // Arrival Time
int pri; // Priority
int queue; // Queue number (for multilevel)
} Process;

// Function for FCFS Scheduling


void FCFS(Process p[], int n) {
printf("\n--- FCFS Scheduling ---\n");
int wt[n], tat[n];
wt[0] = 0;
for (int i = 1; i < n; i++)
wt[i] = wt[i-1] + p[i-1].bt;

for (int i = 0; i < n; i++)


tat[i] = wt[i] + p[i].bt;

printf("PID\tBT\tWT\tTAT\n");
for (int i = 0; i < n; i++)
printf("%d\t%d\t%d\t%d\n", p[i].pid, p[i].bt, wt[i], tat[i]);
}

// Function for SJF Scheduling


void SJF(Process p[], int n) {
printf("\n--- SJF Scheduling ---\n");
Process temp;
int wt[n], tat[n];

// Sort based on Burst Time


for (int i = 0; i < n-1; i++)
for (int j = i+1; j < n; j++)
if (p[j].bt < p[i].bt) {
temp = p[i];
p[i] = p[j];
p[j] = temp;
}

wt[0] = 0;
for (int i = 1; i < n; i++)
wt[i] = wt[i-1] + p[i-1].bt;

for (int i = 0; i < n; i++)


tat[i] = wt[i] + p[i].bt;

printf("PID\tBT\tWT\tTAT\n");
for (int i = 0; i < n; i++)
printf("%d\t%d\t%d\t%d\n", p[i].pid, p[i].bt, wt[i], tat[i]);
}

// Function for Priority Scheduling


void Priority(Process p[], int n) {
printf("\n--- Priority Scheduling ---\n");
Process temp;
int wt[n], tat[n];

// Sort based on Priority (lower number = higher priority)


for (int i = 0; i < n-1; i++)
for (int j = i+1; j < n; j++)
if (p[j].pri < p[i].pri) {
temp = p[i];
p[i] = p[j];
p[j] = temp;
}

wt[0] = 0;
for (int i = 1; i < n; i++)
wt[i] = wt[i-1] + p[i-1].bt;

for (int i = 0; i < n; i++)


tat[i] = wt[i] + p[i].bt;

printf("PID\tBT\tPriority\tWT\tTAT\n");
for (int i = 0; i < n; i++)
printf("%d\t%d\t%d\t\t%d\t%d\n", p[i].pid, p[i].bt, p[i].pri, wt[i],
tat[i]);
}
// Function for Multilevel Queue Scheduling
void MultilevelQueue(Process p[], int n) {
printf("\n--- Multilevel Queue Scheduling ---\n");
Process queue1[MAX], queue2[MAX];
int n1 = 0, n2 = 0;

// Divide into two queues (0 = System, 1 = User)


for (int i = 0; i < n; i++) {
if (p[i].queue == 0)
queue1[n1++] = p[i];
else
queue2[n2++] = p[i];
}

printf("\n[Queue 1: System - FCFS]\n");


FCFS(queue1, n1);

printf("\n[Queue 2: User - Priority]\n");


Priority(queue2, n2);
}

// Main Function
int main() {
Process p[MAX];
int n;

printf("Enter number of processes: ");


scanf("%d", &n);

printf("Enter Process details:\n");


for (int i = 0; i < n; i++) {
p[i].pid = i + 1;
printf("Process %d - BT: ", p[i].pid);
scanf("%d", &p[i].bt);
printf("Process %d - Priority: ", p[i].pid);
scanf("%d", &p[i].pri);
printf("Process %d - Queue (0=System, 1=User): ", p[i].pid);
scanf("%d", &p[i].queue);
}

FCFS(p, n);
SJF(p, n);
Priority(p, n);
MultilevelQueue(p, n);

return 0;
}

🧪 Sample Input
Enter number of processes: 3
Process 1 - BT: 5
Process 1 - Priority: 2
Process 1 - Queue: 0
Process 2 - BT: 3
Process 2 - Priority: 1
Process 2 - Queue: 1
Process 3 - BT: 8
Process 3 - Priority: 3
Process 3 - Queue: 1

🛠 Compile and Run


gcc cpu_sched.c -o cpu_sched
./cpu_sched

Program 4

Implement file storage allocation technique:

i. Contiguous(using array)
ii. Linked �list(using linked-list)
iii. Indirect allocation (indexing)

Solution:
Here's a complete C program implementing file storage allocation techniques:

 i. Contiguous Allocation (using array)


 ii. Linked List Allocation
 iii. Indexed (Indirect) Allocation

Each method is demonstrated with a simple simulation of disk blocks.

✅ C Program: File Storage Allocation Techniques


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_BLOCKS 100

int disk[MAX_BLOCKS]; // 0: free, 1: allocated

// ---------------------------
// Contiguous Allocation
// ---------------------------
void contiguousAllocation() {
int start, length, flag = 0;

printf("\n[Contiguous Allocation]\n");
printf("Enter starting block and length of file: ");
scanf("%d %d", &start, &length);

if (start + length > MAX_BLOCKS) {


printf("Allocation exceeds disk size.\n");
return;
}

for (int i = start; i < start + length; i++) {


if (disk[i] == 1) {
flag = 1;
break;
}
}

if (flag) {
printf("Contiguous blocks not available.\n");
} else {
for (int i = start; i < start + length; i++)
disk[i] = 1;
printf("File allocated at blocks: ");
for (int i = start; i < start + length; i++)
printf("%d ", i);
printf("\n");
}
}

// ---------------------------
// Linked List Allocation
// ---------------------------
typedef struct Node {
int block;
struct Node* next;
} Node;

void linkedListAllocation() {
int n, block;
Node* head = NULL, *temp = NULL, *newNode;

printf("\n[Linked List Allocation]\n");


printf("Enter number of blocks: ");
scanf("%d", &n);

for (int i = 0; i < n; i++) {


printf("Enter block number: ");
scanf("%d", &block);

if (block < 0 || block >= MAX_BLOCKS || disk[block] == 1) {


printf("Invalid or already allocated block.\n");
return;
}

disk[block] = 1;
newNode = (Node*)malloc(sizeof(Node));
newNode->block = block;
newNode->next = NULL;

if (head == NULL)
head = newNode;
else
temp->next = newNode;

temp = newNode;
}

printf("File allocated at blocks: ");


temp = head;
while (temp) {
printf("%d ", temp->block);
temp = temp->next;
}
printf("\n");

// Free linked list


while (head) {
temp = head;
head = head->next;
free(temp);
}
}

// ---------------------------
// Indexed Allocation
// ---------------------------
void indexedAllocation() {
int indexBlock, n, block;

printf("\n[Indexed Allocation]\n");
printf("Enter index block: ");
scanf("%d", &indexBlock);

if (disk[indexBlock] == 1) {
printf("Index block already allocated.\n");
return;
}

printf("Enter number of blocks: ");


scanf("%d", &n);

int blocks[n];
for (int i = 0; i < n; i++) {
printf("Enter block number %d: ", i + 1);
scanf("%d", &blocks[i]);

if (blocks[i] < 0 || blocks[i] >= MAX_BLOCKS || disk[blocks[i]] == 1)


{
printf("Block %d is invalid or already allocated.\n", blocks[i]);
return;
}
}

disk[indexBlock] = 1;
for (int i = 0; i < n; i++)
disk[blocks[i]] = 1;

printf("File indexed at block %d\n", indexBlock);


printf("Allocated data blocks: ");
for (int i = 0; i < n; i++)
printf("%d ", blocks[i]);
printf("\n");
}

// ---------------------------
// Main Function
// ---------------------------
int main() {
int choice;

while (1) {
printf("\n--- File Storage Allocation Menu ---\n");
printf("1. Contiguous Allocation\n");
printf("2. Linked List Allocation\n");
printf("3. Indexed Allocation\n");
printf("4. Exit\n");
printf("Choose method: ");
scanf("%d", &choice);

switch (choice) {
case 1: contiguousAllocation(); break;
case 2: linkedListAllocation(); break;
case 3: indexedAllocation(); break;
case 4: exit(0);
default: printf("Invalid choice!\n");
}
}
return 0;
}

🛠 Compile & Run


gcc file_allocation.c -o file_allocation
./file_allocation

This simulation uses a 1D array to represent the disk (disk[100]). Each method allocates space
differently:

 Contiguous: Allocates blocks in a continuous segment.


 Linked: Uses pointers (linked list).
 Indexed: A single index block holds references to all file blocks.
Program 5

Implementation of contiguous allocation techniques: i. Worst-Fit ii. Best-


Fit iii. First- Fit.

Solution:
Here is a C program that implements Contiguous Memory Allocation Techniques:

 i. Worst-Fit
 ii. Best-Fit
 iii. First-Fit

These algorithms are applied to allocate memory blocks to incoming processes based on
different strategies.

✅ C Program: Contiguous Allocation (Worst, Best, First Fit)


#include <stdio.h>

#define MAX 20

void firstFit(int blockSize[], int m, int processSize[], int n) {


int allocation[n];
for (int i = 0; i < n; i++)
allocation[i] = -1;

for (int i = 0; i < n; i++) {


for (int j = 0; j < m; j++) {
if (blockSize[j] >= processSize[i]) {
allocation[i] = j;
blockSize[j] -= processSize[i];
break;
}
}
}

printf("\nFirst Fit Allocation:\n");


for (int i = 0; i < n; i++) {
printf("Process %d (%d KB) -> ", i + 1, processSize[i]);
if (allocation[i] != -1)
printf("Block %d\n", allocation[i] + 1);
else
printf("Not Allocated\n");
}
}

void bestFit(int blockSize[], int m, int processSize[], int n) {


int allocation[n];
for (int i = 0; i < n; i++)
allocation[i] = -1;

for (int i = 0; i < n; i++) {


int bestIdx = -1;
for (int j = 0; j < m; j++) {
if (blockSize[j] >= processSize[i]) {
if (bestIdx == -1 || blockSize[j] < blockSize[bestIdx])
bestIdx = j;
}
}

if (bestIdx != -1) {
allocation[i] = bestIdx;
blockSize[bestIdx] -= processSize[i];
}
}

printf("\nBest Fit Allocation:\n");


for (int i = 0; i < n; i++) {
printf("Process %d (%d KB) -> ", i + 1, processSize[i]);
if (allocation[i] != -1)
printf("Block %d\n", allocation[i] + 1);
else
printf("Not Allocated\n");
}
}

void worstFit(int blockSize[], int m, int processSize[], int n) {


int allocation[n];
for (int i = 0; i < n; i++)
allocation[i] = -1;

for (int i = 0; i < n; i++) {


int worstIdx = -1;
for (int j = 0; j < m; j++) {
if (blockSize[j] >= processSize[i]) {
if (worstIdx == -1 || blockSize[j] > blockSize[worstIdx])
worstIdx = j;
}
}

if (worstIdx != -1) {
allocation[i] = worstIdx;
blockSize[worstIdx] -= processSize[i];
}
}

printf("\nWorst Fit Allocation:\n");


for (int i = 0; i < n; i++) {
printf("Process %d (%d KB) -> ", i + 1, processSize[i]);
if (allocation[i] != -1)
printf("Block %d\n", allocation[i] + 1);
else
printf("Not Allocated\n");
}
}

int main() {
int blockSize[MAX], processSize[MAX];
int m, n;

printf("Enter number of memory blocks: ");


scanf("%d", &m);
printf("Enter size of each memory block (in KB):\n");
for (int i = 0; i < m; i++) {
printf("Block %d: ", i + 1);
scanf("%d", &blockSize[i]);
}

printf("\nEnter number of processes: ");


scanf("%d", &n);
printf("Enter memory requirement of each process (in KB):\n");
for (int i = 0; i < n; i++) {
printf("Process %d: ", i + 1);
scanf("%d", &processSize[i]);
}

int block1[MAX], block2[MAX], block3[MAX];


for (int i = 0; i < m; i++) {
block1[i] = block2[i] = block3[i] = blockSize[i];
}

firstFit(block1, m, processSize, n);


bestFit(block2, m, processSize, n);
worstFit(block3, m, processSize, n);

return 0;
}

🧪 Sample Input
Enter number of memory blocks: 5
Block 1: 100
Block 2: 500
Block 3: 200
Block 4: 300
Block 5: 600

Enter number of processes: 4


Process 1: 212
Process 2: 417
Process 3: 112
Process 4: 426

🛠 Compile & Run


gcc memory_allocation.c -o memory_allocation
./memory_allocation

This program shows how each algorithm works:

 First Fit: Allocates the first block that is big enough.


 Best Fit: Allocates the smallest sufficient block.
 Worst Fit: Allocates the largest available block.

Program 6

 Calculation of external and internal fragmentation

i. Free space list of blocks from system

ii. List process file from the system.

Solution:

Here's a simple C program that simulates the calculation of Internal and External
Fragmentation, based on:

 i. Free space list (block sizes available)


 ii. Process list (process memory requirements)

✅ Internal vs External Fragmentation

 Internal Fragmentation occurs when a process is allocated a block larger than required
— the leftover is internal.
 External Fragmentation occurs when total free memory is enough, but not in
contiguous blocks large enough to fulfill a request.

💻 C Program: Fragmentation Calculation


#include <stdio.h>

#define MAX 50

int main() {
int blockCount, processCount;
int blocks[MAX], processes[MAX], allocation[MAX];
int i, j;

printf("Enter number of memory blocks: ");


scanf("%d", &blockCount);

printf("Enter size of each block:\n");


for (i = 0; i < blockCount; i++) {
printf("Block %d: ", i + 1);
scanf("%d", &blocks[i]);
}

printf("\nEnter number of processes: ");


scanf("%d", &processCount);

printf("Enter size of each process:\n");


for (i = 0; i < processCount; i++) {
printf("Process %d: ", i + 1);
scanf("%d", &processes[i]);
}

// First-Fit Allocation
for (i = 0; i < processCount; i++) {
allocation[i] = -1;
for (j = 0; j < blockCount; j++) {
if (blocks[j] >= processes[i]) {
allocation[i] = j;
blocks[j] -= processes[i]; // reduce available block
break;
}
}
}

// Calculate fragmentation
int internalFragmentation = 0;
for (i = 0; i < processCount; i++) {
if (allocation[i] != -1)
internalFragmentation += blocks[allocation[i]];
}

int externalFragmentation = 0;
int unallocated = 0;
for (i = 0; i < processCount; i++) {
if (allocation[i] == -1) {
unallocated++;
}
}

if (unallocated > 0) {
for (i = 0; i < blockCount; i++)
externalFragmentation += blocks[i];
}

// Output allocation result


printf("\nProcess Allocation:\n");
for (i = 0; i < processCount; i++) {
printf("Process %d (%d KB) -> ", i + 1, processes[i]);
if (allocation[i] != -1)
printf("Block %d\n", allocation[i] + 1);
else
printf("Not Allocated\n");
}

printf("\nTotal Internal Fragmentation: %d KB\n", internalFragmentation);


if (unallocated > 0)
printf("Total External Fragmentation: %d KB\n",
externalFragmentation);
else
printf("No External Fragmentation (All processes allocated)\n");

return 0;
}

🧪 Sample Input:
Enter number of memory blocks: 4
Block 1: 100
Block 2: 500
Block 3: 200
Block 4: 300

Enter number of processes: 3


Process 1: 212
Process 2: 417
Process 3: 112

🛠 Compile & Run


gcc fragmentation.c -o fragmentation
./fragmentation

This program uses First-Fit strategy and shows how much memory is:

 Wasted inside blocks (internal),


 Wasted outside due to fragmentation of free blocks (external).

Program 7

 Implementation of compaction for the continually changing memory layout and


calculate total movement of data.
Here’s a C program that simulates memory compaction — a process of rearranging memory so
that all free memory is in one large contiguous block — and calculates the total data moved
during compaction.

✅ Features:

 Simulates memory blocks (used + free).


 Simulates processes occupying memory (with starting address and size).
 Compacts memory by moving all processes together to remove external fragmentation.
 Calculates total data movement during compaction.

💻 C Program: Memory Compaction Simulation


#include <stdio.h>

#define MAX 20

typedef struct {
int pid; // Process ID
int start; // Start address
int size; // Memory size
} Process;

int main() {
int n, memorySize, totalMoved = 0;
Process processes[MAX];

printf("Enter total memory size: ");


scanf("%d", &memorySize);

printf("Enter number of processes: ");


scanf("%d", &n);

// Input processes
for (int i = 0; i < n; i++) {
printf("Enter Process ID, Start Address, and Size (in KB) for Process
%d: ", i + 1);
scanf("%d%d%d", &processes[i].pid, &processes[i].start,
&processes[i].size);
}

// Sort processes based on their start address


for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (processes[j].start > processes[j + 1].start) {
Process temp = processes[j];
processes[j] = processes[j + 1];
processes[j + 1] = temp;
}
}
}

printf("\nBefore Compaction:\n");
for (int i = 0; i < n; i++) {
printf("Process %d: Start = %d, Size = %d\n", processes[i].pid,
processes[i].start, processes[i].size);
}

// Perform Compaction
int currentStart = 0;
for (int i = 0; i < n; i++) {
if (processes[i].start != currentStart) {
totalMoved += processes[i].size;
processes[i].start = currentStart;
}
currentStart += processes[i].size;
}

printf("\nAfter Compaction:\n");
for (int i = 0; i < n; i++) {
printf("Process %d: New Start = %d, Size = %d\n", processes[i].pid,
processes[i].start, processes[i].size);
}

printf("\nTotal Data Moved During Compaction = %d KB\n", totalMoved);


printf("Free memory starts at address = %d and size = %d KB\n",
currentStart, memorySize - currentStart);

return 0;
}

🧪 Sample Input:
Enter total memory size: 1000
Enter number of processes: 3
Process 1: 1 100 200
Process 2: 2 400 150
Process 3: 3 700 100

🧾 Output:
Before Compaction:
Process 1: Start = 100, Size = 200
Process 2: Start = 400, Size = 150
Process 3: Start = 700, Size = 100

After Compaction:
Process 1: New Start = 0, Size = 200
Process 2: New Start = 200, Size = 150
Process 3: New Start = 350, Size = 100
Total Data Moved During Compaction = 300 KB
Free memory starts at address = 450 and size = 550 KB

Program 8

 Implementation of resource allocation graph RAG.

Here's a C program to implement a Resource Allocation Graph (RAG), which is used to


model the state of a system with processes and resources, and can help detect deadlocks.

✅ What the program does:

 Models processes and resources as a bipartite graph.


 Allows adding:
o Request edges (P → R): A process requests a resource.
o Assignment edges (R → P): A resource is assigned to a process.
 Prints the adjacency matrix (RAG).
 Optionally can help detect cycles (deadlocks).

💻 C Program: Resource Allocation Graph (RAG)


#include <stdio.h>
#include <stdlib.h>

#define MAX 20

int main() {
int p, r; // number of processes and resources
int rag[MAX][MAX] = {0}; // adjacency matrix
char nodeName[MAX][10]; // node names

printf("Enter number of processes: ");


scanf("%d", &p);
printf("Enter number of resources: ");
scanf("%d", &r);

int total = p + r;

// Naming nodes
for (int i = 0; i < p; i++)
sprintf(nodeName[i], "P%d", i + 1);
for (int i = 0; i < r; i++)
sprintf(nodeName[p + i], "R%d", i + 1);

// Input request and assignment edges


int edges;
printf("Enter number of edges (requests and assignments): ");
scanf("%d", &edges);

printf("Enter each edge in format: FromNodeIndex ToNodeIndex (0-based


index)\n");
printf("Note: Process indices: 0 to %d, Resource indices: %d to %d\n", p -
1, p, total - 1);
for (int i = 0; i < edges; i++) {
int from, to;
printf("Edge %d: ", i + 1);
scanf("%d%d", &from, &to);
rag[from][to] = 1;
}

// Display RAG
printf("\nResource Allocation Graph (Adjacency Matrix):\n ");
for (int i = 0; i < total; i++)
printf("%4s", nodeName[i]);
printf("\n");

for (int i = 0; i < total; i++) {


printf("%4s", nodeName[i]);
for (int j = 0; j < total; j++)
printf("%4d", rag[i][j]);
printf("\n");
}

return 0;
}

🧪 Sample Input:
Enter number of processes: 2
Enter number of resources: 2
Enter number of edges: 4

Edge 1: 0 2 // P1 requests R1
Edge 2: 2 1 // R1 assigned to P2
Edge 3: 1 3 // P2 requests R2
Edge 4: 3 0 // R2 assigned to P1

✅ This forms a cycle: P1 → R1 → P2 → R2 → P1 (deadlock).

🧾 Sample Output:
Resource Allocation Graph (Adjacency Matrix):
P1 P2 R1 R2
P1 0 0 1 0
P2 0 0 0 1
R1 0 1 0 0
R2 1 0 0 0

🔁 Additions You Can Make:

 Detect cycle in the graph (for deadlock detection).


 Visualize using a graph-drawing tool or matrix plot.

Program 9

 Implementation of Banker?s algorithm.

Here's a C program to implement the Banker's Algorithm, which is used in operating systems
to avoid deadlock by checking for a safe sequence of process execution.

✅ Features:

 Accepts input for:


o Number of processes and resources.
o Allocation matrix (current resource allocation).
o Maximum matrix (maximum demand).
o Available resources.
 Computes the Need matrix.
 Checks for a safe sequence using Banker's Algorithm.
 Reports whether the system is in a safe state or not.

💻 C Program: Banker's Algorithm


#include <stdio.h>
#include <stdbool.h>

#define MAX 10

int main() {
int n, m; // n = number of processes, m = number of resources
int alloc[MAX][MAX], max[MAX][MAX], need[MAX][MAX];
int avail[MAX];
bool finish[MAX] = {false};
int safeSeq[MAX], count = 0;

printf("Enter number of processes: ");


scanf("%d", &n);

printf("Enter number of resource types: ");


scanf("%d", &m);

printf("Enter Allocation Matrix:\n");


for (int i = 0; i < n; i++) {
printf("Process %d: ", i);
for (int j = 0; j < m; j++)
scanf("%d", &alloc[i][j]);
}

printf("Enter Maximum Matrix:\n");


for (int i = 0; i < n; i++) {
printf("Process %d: ", i);
for (int j = 0; j < m; j++)
scanf("%d", &max[i][j]);
}

printf("Enter Available Resources:\n");


for (int i = 0; i < m; i++)
scanf("%d", &avail[i]);

// Calculate Need matrix


for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
need[i][j] = max[i][j] - alloc[i][j];

// Banker's Algorithm to find safe sequence


while (count < n) {
bool found = false;
for (int i = 0; i < n; i++) {
if (!finish[i]) {
int j;
for (j = 0; j < m; j++)
if (need[i][j] > avail[j])
break;

if (j == m) {
// This process can be completed
for (int k = 0; k < m; k++)
avail[k] += alloc[i][k];

safeSeq[count++] = i;
finish[i] = true;
found = true;
}
}
}

if (!found) {
printf("\nSystem is NOT in a safe state (Deadlock possible)\n");
return 1;
}
}

// Print safe sequence


printf("\nSystem is in a SAFE state.\nSafe sequence is: ");
for (int i = 0; i < n; i++) {
printf("P%d", safeSeq[i]);
if (i != n - 1) printf(" -> ");
}
printf("\n");

return 0;
}

🧪 Sample Input:
Processes: 5
Resources: 3

Allocation Matrix:
P0: 0 1 0
P1: 2 0 0
P2: 3 0 2
P3: 2 1 1
P4: 0 0 2

Maximum Matrix:
P0: 7 5 3
P1: 3 2 2
P2: 9 0 2
P3: 2 2 2
P4: 4 3 3

Available Resources: 3 3 2

✅ Output:
System is in a SAFE state.
Safe sequence is: P1 -> P3 -> P4 -> P0 -> P2

Let me know if you’d like this with resource request simulation, GUI visualization, or
C++/Python version.

You might also like