OS 250213107005
# Complete OS Scheduling & Resource Management Algorithms
## All Code with Detailed Comments - Single Reference Document
## TABLE OF CONTENTS
1. [FCFS Disk Scheduling](#1-fcfs-disk-scheduling)
2. [Priority CPU Scheduling](#2-priority-cpu-scheduling)
3. [SJF CPU Scheduling](#3-sjf-cpu-scheduling)
4. [Memory Allocation Algorithms](#4-memory-allocation-algorithms)
5. [Banker's Algorithm](#5-bankers-algorithm)
# 1. FCFS DISK SCHEDULING
## Overview
FCFS (First Come First Served) processes disk requests in the order they arrive.
Simple but not optimized.
## Complete Code with Comments
==========================================================
==================
* FCFS (First Come First Served) Disk Scheduling Algorithm
*
==========================================================
==================
*
* PURPOSE:
* Simulates FCFS disk scheduling - processes requests in arrival order.
* Calculates total head movement (distance disk head travels).
*
* HOW IT WORKS:
* 1. Get number of disk requests
* 2. Get all disk request cylinder positions
* 3. Get initial disk head position
* 4. For each request (in order as given):
* - Calculate distance from current position to requested position
* - Move disk head to that position
* - Update current position
GEC Bhavnagar
OS 250213107005
* 5. Print total and average movement
*
* FORMULA:
* Movement = |Current Position - Requested Position|
* Total = Sum of all movements
* Average = Total / Number of Requests
*
==========================================================
==================
*/
#include <stdio.h> // For input/output operations
#include <stdlib.h> // For abs() function to calculate absolute values
int main() {
//
==========================================================
==============
// STEP 1: INPUT - Get number of requests and their positions
==========================================================
==============
int n; // Variable to store number of disk requests
printf("Enter number of disk requests: ");
scanf("%d", &n); // Read number of requests from user
int req[n]; // Array to store disk request cylinder positions
printf("Enter disk request sequence: ");
for (int i = 0; i < n; i++)
scanf("%d", &req[i]); // Read each request position
int head; // Variable for initial disk head position
printf("Enter initial head position: ");
scanf("%d", &head); // Read starting position of disk head
==========================================================
==============
// STEP 2: INITIALIZE - Set up variables for calculation
==========================================================
==============
int total = 0; // Total head movement (accumulator)
int current = head; // Current head position (starts at initial position)
GEC Bhavnagar
OS 250213107005
==========================================================
==============
// STEP 3: PROCESS REQUESTS - Print table and calculate movements
//
==========================================================
==============
// Print table header - shows what each column means
printf("\nOrder\tFrom\tTo\tMovement\n");
printf("----------------------------------\n");
// MAIN LOOP: Process each disk request in FCFS order (one by one, as
given)
for (int i = 0; i < n; i++) {
// Calculate how far disk head needs to move
// Absolute value makes it always positive (distance is always positive)
// Example: Moving from 50 to 82 = |50-82| = |-32| = 32
int move = abs(current - req[i]);
// Print results for this request:
// i+1 = order number (starts from 1, not 0)
// current = where head is now
// req[i] = where we need to go (the request)
// move = how far we need to move
printf("%d\t%d\t%d\t%d\n", i+1, current, req[i], move);
// Add this movement to total
// total = total + move (keeps running sum)
total += move;
// Update current position to the position we just serviced
// For next request, we start from where we are now
current = req[i];
}
//
==========================================================
==============
GEC Bhavnagar
OS 250213107005
// STEP 4: OUTPUT - Print final results
==========================================================
==============
// Print total head movement in cylinders
printf("\nTotal Head Movement : %d cylinders\n", total);
// Calculate and print average: convert to float for decimal result
// Example: total=100, n=5, average=100/5=20.00
printf("Average Movement : %.2f cylinders\n", (float)total / n);
return 0; // Program ends successfully
}
## Example Execution
Input:
5 disk requests
Positions: 50 82 10 67 30
Starting position: 53
Processing:
Request 1: 53 → 50 = 3 units
Request 2: 50 → 82 = 32 units
Request 3: 82 → 10 = 72 units
Request 4: 10 → 67 = 57 units
Request 5: 67 → 30 = 37 units
Output:
Total = 201 cylinders
Average = 40.20 cylinders
GEC Bhavnagar
OS 250213107005
# 2. PRIORITY CPU SCHEDULING
## Overview
Priority Scheduling executes processes based on priority values. Higher priority
(lower number) processes run first.
==========================================================
==================
* Priority Scheduling Algorithm (Non-Preemptive)
==========================================================
==================
*
* PURPOSE:
* Schedules CPU processes based on priority values.
* Lower priority number = Higher priority = Executes first
*
* TERMS:
* Burst Time (BT) = How long the process needs the CPU
* Priority = Importance level (1=highest, 5=lowest)
* Waiting Time (WT) = Time process waits before execution
* Turnaround Time (TAT) = Total time from arrival to completion
*
* HOW IT WORKS:
* 1. Read process count
* 2. Input burst time and priority for each process
* 3. Sort by priority (ascending order - higher priority first)
* 4. Calculate waiting time for each process
* 5. Calculate turnaround time (WT + BT)
* 6. Display results and averages
*
* FORMULAS:
* WT[0] = 0 (first process waits 0 time)
* WT[i] = WT[i-1] + BT[i-1] (sum of all previous burst times)
* TAT[i] = WT[i] + BT[i]
* Avg WT = Sum(WT) / n
* Avg TAT = Sum(TAT) / n
*
==========================================================
==================
#include <stdio.h>
GEC Bhavnagar
OS 250213107005
// Define a structure to hold process information
struct Process {
int id; // Process ID (P1, P2, P3, etc.)
int bt; // Burst Time (how long it needs CPU)
int priority; // Priority (lower number = higher priority)
int wt; // Waiting Time (calculated)
int tat; // Turnaround Time (calculated)
};
int main() {
//
==========================================================
==============
// STEP 1: INPUT - Get number of processes
//
==========================================================
==============
int n; // Variable to store number of processes
printf("Enter number of processes: ");
scanf("%d", &n);
// Create array of processes
struct Process p[n];
==========================================================
==============
// STEP 2: INPUT - Get burst time and priority for each process
//
==========================================================
==============
for (int i = 0; i < n; i++) {
// Set process ID (1-based, not 0-based)
p[i].id = i + 1;
// Ask user for input
printf("Enter burst time and priority for P%d: ", i+1);
// Read both values on same line
// Example input: "2 5" means burst time=2, priority=5
scanf("%d %d", &p[i].bt, &p[i].priority);
GEC Bhavnagar
OS 250213107005
//
==========================================================
==============
// STEP 3: SORT - Sort processes by priority (ascending = higher first)
//
==========================================================
==============
// Bubble sort algorithm - compare and swap if needed
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
// If current priority is higher (larger number) than next
// swap them so higher priority (lower number) comes first
if (p[i].priority > p[j].priority) {
// Swap using temporary variable
struct Process temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
==========================================================
==============
// STEP 4: CALCULATE - Compute waiting times
//
==========================================================
==============
// First process waits 0 time (no one ahead of it)
p[0].wt = 0;
// For other processes: waiting time = sum of all previous burst times
for (int i = 1; i < n; i++) {
// WT[i] = WT[i-1] + BT[i-1]
// Example: P2 waits = (P1's wait) + (P1's burst time)
p[i].wt = p[i-1].wt + p[i-1].bt;
}
==========================================================
==============
GEC Bhavnagar
OS 250213107005
// STEP 5: CALCULATE - Compute turnaround times and totals //
==========================================================
==============
int total_wt = 0; // Accumulator for total waiting time
int total_tat = 0; // Accumulator for total turnaround time
// Print table header
printf("\nPID\tBT\tPriority\tWT\tTAT\n");
printf("------------------------------------------\n");
// Calculate TAT for each process and accumulate totals
for (int i = 0; i < n; i++) {
// Turnaround Time = Waiting Time + Burst Time
// TAT = how long from arrival until process finishes
p[i].tat = p[i].wt + p[i].bt;
// Add to running totals
total_wt += p[i].wt; // Keep sum of all waiting times
total_tat += p[i].tat; // Keep sum of all turnaround times
// Print process information in table format
printf("P%d\t%d\t%d\t\t%d\t%d\n",
p[i].id, p[i].bt, p[i].priority, p[i].wt, p[i].tat);
}
==========================================================
==============
// STEP 6: OUTPUT - Print averages
==========================================================
==============
// Calculate average waiting time (convert to float for decimals)
printf("\nAvg Waiting Time : %.2f\n", (float)total_wt / n);
// Calculate average turnaround time
printf("Avg Turnaround Time : %.2f\n", (float)total_tat / n);
return 0; // Program ends successfully
}
## Example Execution
GEC Bhavnagar
OS 250213107005
```
Input:
4 processes
P1: BT=2, Priority=5
P2: BT=1, Priority=3
P3: BT=6, Priority=4
P4: BT=2, Priority=1
After Sorting by Priority:
P4 (Priority 1) - executes FIRST
P2 (Priority 3)
P3 (Priority 4)
P1 (Priority 5) - executes LAST
Calculations:
P4: WT=0, TAT=0+2=2
P2: WT=2, TAT=2+1=3
P3: WT=3, TAT=3+6=9
P1: WT=9, TAT=9+2=11
Output:
Average Waiting Time = 3.50
Average Turnaround Time = 6.25
```
# 3. SJF CPU SCHEDULING
## Overview
Shortest Job First executes processes with smallest burst time first. Minimizes
average waiting time.
==========================================================
==================
* SJF (Shortest Job First) Scheduling Algorithm
GEC Bhavnagar
OS 250213107005
*=========================================================
===================
*
* PURPOSE:
* Schedules processes based on burst time - shortest jobs execute first.
* Achieves minimum average waiting time (theoretically optimal).
*
* TERMS:
* Burst Time (BT) = Time needed for process to complete
* Waiting Time (WT) = Time process spends waiting in queue
* Turnaround Time (TAT) = WT + BT (total time)
*
* HOW IT WORKS:
* 1. Read process count
* 2. Input burst time for each process
* 3. Sort by burst time (ascending - smallest first)
* 4. Calculate waiting times
* 5. Calculate turnaround times
* 6. Display results
*
* KEY ADVANTAGE:
* Minimizes average waiting time compared to FCFS.
* One of the best algorithms for average metrics.
*
* KEY DISADVANTAGE:
* Starvation - long processes may wait forever if short jobs keep arriving.
*
#include <stdio.h>
// Define process structure
struct Process {
int id; // Process identifier
int bt; // Burst time (job duration)
int wt; // Waiting time (calculated)
int tat; // Turnaround time (calculated)
};
GEC Bhavnagar
OS 250213107005
// Function to execute SJF scheduling algorithm
void sjf(struct Process p[], int n) {
//
==========================================================
==========
// STEP 1: SORT - Sort processes by burst time (ascending order)
//
==========================================================
==========
// Bubble Sort: Compare adjacent elements and swap if needed
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
// If current burst time is MORE than next burst time
// Then swap (put shorter job first)
if (p[i].bt > p[j].bt) {
// Swap using temporary variable
struct Process temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
==========================================================
==========
// STEP 2: CALCULATE - Waiting times
//
==========================================================
==========
// First process waits 0 time
p[0].wt = 0;
// Accumulator for totals
int total_wt = 0, total_tat = 0;
// Calculate waiting time for each process after the first
GEC Bhavnagar
OS 250213107005
for (int i = 1; i < n; i++) {
// WT[i] = WT[i-1] + BT[i-1]
// Current process waits for all previous processes to finish
p[i].wt = p[i-1].wt + p[i-1].bt;
}
//
==========================================================
==========
// STEP 3: DISPLAY - Print table header
//
==========================================================
==========
printf("\nPID\tBT\tWT\tTAT\n");
printf("-----------------------------\n");
//
==========================================================
==========
// STEP 4: CALCULATE & DISPLAY - Process each job
//
==========================================================
==========
for (int i = 0; i < n; i++) {
// Calculate turnaround time = waiting time + burst time
// TAT is total time from when process arrives to when it completes
p[i].tat = p[i].wt + p[i].bt;
// Add to running totals
total_wt += p[i].wt; // Sum all waiting times
total_tat += p[i].tat; // Sum all turnaround times
// Print table row for this process
printf("P%d\t%d\t%d\t%d\n", p[i].id, p[i].bt, p[i].wt, p[i].tat);
}
GEC Bhavnagar
OS 250213107005
//
==========================================================
==========
// STEP 5: OUTPUT - Print averages
//
==========================================================
==========
// Calculate and display average waiting time
printf("\nAvg Waiting Time : %.2f\n", (float)total_wt / n);
// Calculate and display average turnaround time
printf("Avg Turnaround Time : %.2f\n", (float)total_tat / n);
}
// Main program
int main() {
int n;
printf("Enter number of processes: ");
scanf("%d", &n);
// Create array of processes
struct Process p[n];
// Input burst time for each process
for (int i = 0; i < n; i++) {
p[i].id = i + 1; // Set process ID
printf("Enter burst time for P%d: ", i + 1);
scanf("%d", &p[i].bt); // Read burst time
}
// Call SJF scheduling function
sjf(p, n);
return 0; // Program ends
}
## Example Execution
Input:
4 processes
GEC Bhavnagar
OS 250213107005
P1: BT=8
P2: BT=4
P3: BT=2
P4: BT=1
After Sorting by Burst Time:
P4 (BT=1) - runs FIRST
P3 (BT=2)
P2 (BT=4)
P1 (BT=8) - runs LAST
Calculations:
P4: WT=0, TAT=0+1=1
P3: WT=1, TAT=1+2=3
P2: WT=3, TAT=3+4=7
P1: WT=7, TAT=7+8=15
Output:
Average Waiting Time = 2.75
Average Turnaround Time = 6.50
GEC Bhavnagar
OS 250213107005
# 4. MEMORY ALLOCATION ALGORITHMS
## Overview
Three strategies for allocating memory blocks to processes: First Fit, Best Fit,
Worst Fit.
## Complete Code with Comments
==========================================================
==================
* Memory Allocation Algorithms: First Fit, Best Fit, Worst Fit
*
==========================================================
==================
*
* PURPOSE:
* Demonstrates three main strategies for allocating memory blocks to
* processes. Each strategy has different fragmentation characteristics.
*
* ALGORITHMS:
* 1. FIRST FIT: Use first available block that fits
* 2. BEST FIT: Use smallest block that fits
* 3. WORST FIT: Use largest available block
*
* FRAGMENTATION:
* External: Free memory scattered, cannot allocate contiguous space
* Internal: Allocated block larger than needed
*
==========================================================
==================
#include <stdio.h>
#define MAX 10
//
==========================================================
==================
// ALGORITHM 1: FIRST FIT
//
==========================================================
==================
GEC Bhavnagar
OS 250213107005
// Strategy: Allocate to FIRST block that is large enough
// Pro: Fast, simple
// Con: May leave large gaps, creates fragmentation
void firstFit(int blocks[], int m, int proc[], int n) {
// m = number of memory blocks
// n = number of processes
// Create allocation array: -1 = not allocated, other = block number
int alloc[n];
// Initialize all as not allocated
for (int i = 0; i < n; i++)
alloc[i] = -1;
// For each process
for (int i = 0; i < n; i++) {
// Search through all memory blocks
for (int j = 0; j < m; j++) {
// If block has enough space for this process
if (blocks[j] >= proc[i]) {
// Allocate: store which block was used
alloc[i] = j;
// Reduce block size (simulate allocation)
blocks[j] -= proc[i];
// Move to next process (found a block)
break;
}
}
}
// Print results
printf("\n--- First Fit ---\n");
for (int i = 0; i < n; i++)
printf("Process %d (%dKB) -> %s\n", i+1, proc[i],
alloc[i] != -1 ? "Allocated" : "Not Allocated");
}
GEC Bhavnagar
OS 250213107005
//
==========================================================
==================
// ALGORITHM 2: BEST FIT
==========================================================
==================
// Strategy: Allocate to SMALLEST block that fits
// Pro: Minimizes wasted space
// Con: Slow (must search all blocks), creates tiny fragments
void bestFit(int blocks[], int m, int proc[], int n) {
// Allocation array
int alloc[n];
// Temporary copy of blocks (don't modify original)
int temp[m];
for (int i = 0; i < m; i++)
temp[i] = blocks[i];
// Initialize allocations as not allocated
for (int i = 0; i < n; i++)
alloc[i] = -1;
// For each process
for (int i = 0; i < n; i++) {
// Find BEST (smallest sufficient) block
int best = -1;
// Search all blocks
for (int j = 0; j < m; j++) {
// If this block can fit the process
if (temp[j] >= proc[i]) {
// If no best found yet, or this block is smaller than previous best
// Choose this block (it's the smallest that fits so far)
if (best == -1 || temp[j] < temp[best])
best = j;
}
}
// If a suitable block was found
GEC Bhavnagar
OS 250213107005
if (best != -1) {
// Allocate to this best block
alloc[i] = best;
// Reduce block size
temp[best] -= proc[i];
}
}
// Print results
printf("\n--- Best Fit ---\n");
for (int i = 0; i < n; i++)
printf("Process %d (%dKB) -> %s\n", i+1, proc[i],
alloc[i] != -1 ? "Allocated" : "Not Allocated");
}
//
==========================================================
==================
// ALGORITHM 3: WORST FIT
//
==========================================================
==================
// Strategy: Allocate to LARGEST available block
// Pro: Leaves largest remaining space
// Con: High failure rate, wasteful
void worstFit(int blocks[], int m, int proc[], int n) {
// Allocation array
int alloc[n];
// Temporary copy of blocks
int temp[m];
for (int i = 0; i < m; i++)
temp[i] = blocks[i];
// Initialize allocations
for (int i = 0; i < n; i++)
alloc[i] = -1;
GEC Bhavnagar
OS 250213107005
// For each process
for (int i = 0; i < n; i++) {
// Find WORST (largest sufficient) block
int worst = -1;
// Search all blocks
for (int j = 0; j < m; j++) {
// If this block can fit the process
if (temp[j] >= proc[i]) {
// If no worst found yet, or this block is larger than previous worst
// Choose this block (it's the largest that fits so far)
if (worst == -1 || temp[j] > temp[worst])
worst = j;
}
}
// If suitable block found
if (worst != -1) {
// Allocate to this worst block
alloc[i] = worst;
// Reduce block size
temp[worst] -= proc[i];
}
}
// Print results
printf("\n--- Worst Fit ---\n");
for (int i = 0; i < n; i++)
printf("Process %d (%dKB) -> %s\n", i+1, proc[i],
alloc[i] != -1 ? "Allocated" : "Not Allocated");
}
==========================================================
// MAIN PROGRAM
int main() {
// Define available memory blocks (in KB)
int blocks[] = {100, 500, 200, 300, 600};
// Define process sizes (in KB)
GEC Bhavnagar
OS 250213107005
int proc[] = {212, 417, 112, 426};
// m = 5 blocks, n = 4 processes
int m = 5, n = 4;
// Create backup copies for Best Fit and Worst Fit
// (because algorithms modify the blocks array)
int b1[5], b2[5];
for (int i = 0; i < m; i++)
b1[i] = b2[i] = blocks[i];
// Run all three algorithms
firstFit(blocks, m, proc, n); // Test 1: First Fit
bestFit(b1, m, proc, n); // Test 2: Best Fit
worstFit(b2, m, proc, n); // Test 3: Worst Fit
return 0; // Program ends
}
## Example Comparison
Available Blocks: 100, 500, 200, 300, 600 KB
Processes: 212, 417, 112, 426 KB
FIRST FIT:
P1 (212): Block 2 (500) → Remaining: 288
P2 (417): Block 5 (600) → Remaining: 183
P3 (112): Block 2 (288) → Remaining: 176
P4 (426): Failed
BEST FIT:
P1 (212): Block 3 (300) → Smallest fit
P2 (417): Block 2 (500) → Smallest fit
P3 (112): Block 2 (Remaining) → Smallest fit
P4 (426): Failed
WORST FIT:
P1 (212): Block 5 (600) → Largest
P2 (417): Block 2 (500) → Largest
P3 (112): Block 5 (388) → Largest
P4 (426): Failed
GEC Bhavnagar
OS 250213107005
# 5. BANKER'S ALGORITHM
## Overview
Banker's Algorithm prevents deadlock by checking if resource allocation keeps
the system in a safe state.
## Complete Code with Comments
```c
/*
*
==========================================================
==================
* Banker's Algorithm - Deadlock Avoidance
*
==========================================================
==================
*
* PURPOSE:
* Prevents deadlock by ensuring resources are allocated only if the
* resulting state is safe (i.e., all processes can eventually complete).
*
* KEY CONCEPTS:
* Safe State: A sequence of process execution exists where all complete
* Unsafe State: No such sequence exists (potential deadlock)
* Allocation: Resources currently assigned to process
* Max: Maximum resources process will ever need
* Need: Remaining resources (Max - Allocation)
* Available: Free resources in the system
*
* HOW IT WORKS:
* 1. Input allocation matrix (what each process currently has)
* 2. Input max matrix (what each process will ever need)
* 3. Calculate need matrix (max - allocation)
* 4. Input available resources
* 5. Run safety algorithm to find safe sequence
* 6. If safe sequence exists: System is safe
* If no safe sequence: System is unsafe (deny allocation)
*
GEC Bhavnagar
OS 250213107005
* SAFETY ALGORITHM:
* Find an order to execute all processes such that:
* - Each process can get remaining resources
* - Each process completes and releases its resources
*
==========================================================
==================
*/
#include <stdio.h>
int main() {
//
==========================================================
==========
// STEP 1: INPUT - Get system configuration
//
==========================================================
==========
int p, r; // p = number of processes, r = number of resource types
printf("Enter number of processes and resources: ");
scanf("%d %d", &p, &r);
// Declare matrices
// alloc[i][j] = resources of type j currently allocated to process i
int alloc[p][r];
// max[i][j] = maximum resources of type j that process i will need
int max[p][r];
// need[i][j] = remaining resources of type j that process i needs
// Formula: need[i][j] = max[i][j] - alloc[i][j]
int need[p][r];
// avail[j] = available resources of type j in the system
int avail[r];
// done[i] = flag showing if process i has completed (1=done, 0=not done)
int done[p];
GEC Bhavnagar
OS 250213107005
// safe[i] = stores the safe sequence of processes
int safe[p];
//
==========================================================
==========
// STEP 2: INPUT - Read allocation matrix
//
==========================================================
==========
printf("Enter Allocation Matrix:\n");
for (int i = 0; i < p; i++) {
for (int j = 0; j < r; j++) {
scanf("%d", &alloc[i][j]);
}
}
//
==========================================================
==========
// STEP 3: INPUT & CALCULATE - Read max matrix and calculate need
//
==========================================================
==========
printf("Enter Max Matrix:\n");
for (int i = 0; i < p; i++) {
for (int j = 0; j < r; j++) {
scanf("%d", &max[i][j]);
// Calculate Need: what process still needs
// Example: If process has 2 resources but needs maximum 5
// Then it needs 3 more
need[i][j] = max[i][j] - alloc[i][j];
}
}
GEC Bhavnagar
OS 250213107005
//
==========================================================
==========
// STEP 4: INPUT - Read available resources
//
==========================================================
==========
printf("Enter Available Resources: ");
for (int i = 0; i < r; i++)
scanf("%d", &avail[i]);
//
==========================================================
==========
// STEP 5: SAFETY ALGORITHM - Find safe sequence
//
==========================================================
==========
// Initialize: no process has completed yet
for (int i = 0; i < p; i++)
done[i] = 0;
// Try to complete all p processes
int count = 0; // How many processes have we completed
// Keep looking for processes to complete until we've processed all
while (count < p) {
int found = 0; // Flag: did we find a process that could complete?
// Look at each process
for (int i = 0; i < p; i++) {
// If this process hasn't completed yet
if (!done[i]) {
// Check: Does this process have remaining needs?
// Check all resource types
int j;
GEC Bhavnagar
OS 250213107005
for (j = 0; j < r; j++) {
// If we don't have enough of resource type j
if (need[i][j] > avail[j])
break; // Process can't complete, stop checking
}
// If loop completed all resources (j == r)
// It means we have enough of ALL resource types
if (j == r) {
// This process can complete!
// When process completes, it releases its resources
// Add allocated resources back to available pool
for (int k = 0; k < r; k++)
avail[k] += alloc[i][k];
// Record this process in safe sequence
safe[count++] = i;
// Mark process as completed
done[i] = 1;
// Signal that we found at least one process to complete
found = 1;
}
}
}
// If we didn't find ANY process that could complete
if (!found) {
// Then there's no way to complete all processes
// System is UNSAFE (potential deadlock)
printf("System is NOT in a safe state!\n");
return 0; // Exit program
}
}
//
==========================================================
==========
GEC Bhavnagar
OS 250213107005
// STEP 6: OUTPUT - Print safe sequence found
//
==========================================================
==========
printf("System is in SAFE STATE.\nSafe Sequence: ");
// Print the safe sequence
for (int i = 0; i < p; i++) {
printf("P%d", safe[i]); // Print process ID
// Add arrow between processes, but not after last
if (i < p - 1)
printf(" -> ");
}
printf("\n");
return 0; // Program ends successfully
}
```
## Example Execution
```
Input:
3 processes, 2 resource types
Allocation Matrix:
P0: 1, 1
P1: 2, 0
P2: 3, 1
Max Matrix:
P0: 7, 5
P1: 3, 2
P2: 9, 2
Available: 2, 1
Safety Algorithm:
GEC Bhavnagar
OS 250213107005
Step 1: P1 needs (1,2), available (2,1) → Need not met
Step 2: P0 needs (6,4), available (2,1) → Need not met
Step 3: P2 needs (6,1), available (2,1) → Need not met
Re-check:
Step 1: P1 needs (1,2), available (2,1) → Still not enough!
Result: System is NOT in a safe state!
## SUMMARY TABLE
| Algorithm | Type | Purpose | Best For |
|-----------|------|---------|----------|
| FCFS Disk | I/O | Disk request scheduling | Fairness |
| Priority | CPU | Process scheduling | Real-time systems |
| SJF | CPU | Process scheduling | Average optimization |
| Memory Alloc | Memory | Block allocation | Fragmentation management |
| Banker's | Deadlock | Prevention/Avoidance | Safety guarantee |
## KEY FORMULAS REFERENCE
### Scheduling Algorithms
```
Waiting Time = Sum of burst times of all previous processes
Turnaround Time = Waiting Time + Burst Time
Average WT = Sum(WT) / Number of Processes
Average TAT = Sum(TAT) / Number of Processes
```
### Disk Scheduling
Head Movement = |Current Position - Next Position|
Total Movement = Sum of all head movements
Average Movement = Total Movement / Number of Requests
### Banker's Algorithm
Need[i][j] = Max[i][j] - Allocation[i][j]
System is safe if a sequence exists where all processes complete
GEC Bhavnagar