Write a program using C to implement Shortest Remaining Time First (SRTF) scheduling algorithm.
Below is the C program that implements the Shortest Remaining Time First (SRTF) scheduling algorithm. SRTF is a preemptive version of the Shortest Job First (SJF) scheduling algorithm, where the process with the least remaining time is given priority.
#include <stdio.h>
struct Process {
int id; // Process ID
int burst; // Burst time
int remaining; // Remaining time
int waiting; // Waiting time
int turnaround; // Turnaround time
};
void calculateTimes(struct Process processes[], int n) {
int total_waiting = 0, total_turnaround = 0;
for (int i = 0; i < n; i++) {
processes[i].turnaround = processes[i].waiting + processes[i].burst;
total_turnaround += processes[i].turnaround;
total_waiting += processes[i].waiting;
}
printf("Average Waiting Time: %.2f\n", (float)total_waiting / n);
printf("Average Turnaround Time: %.2f\n", (float)total_turnaround / n);
}
int findShortestRemainingProcess(struct Process processes[], int n, int current_time) {
int idx = -1;
for (int i = 0; i < n; i++) {
if (processes[i].remaining > 0) {
if (idx == -1 || processes[i].remaining < processes[idx].remaining) {
idx = i;
}
}
}
return idx;
}
int main() {
int n;
// Read the number of processes
printf("Enter the number of processes: ");
scanf("%d", &n);
struct Process processes[n];
// Read process burst times
for (int i = 0; i < n; i++) {
processes[i].id = i + 1; // Assign Process ID
printf("Enter burst time for Process %d: ", i + 1);
scanf("%d", &processes[i].burst);
processes[i].remaining = processes[i].burst; // Initialize remaining time
processes[i].waiting = 0; // Initialize waiting time
}
int current_time = 0;
int completed = 0;
// Process scheduling loop
while (completed < n) {
int idx = findShortestRemainingProcess(processes, n, current_time);
if (idx != -1) {
// Process the shortest remaining job
processes[idx].remaining--;
current_time++;
// Check if the process is completed
if (processes[idx].remaining == 0) {
processes[idx].turnaround = current_time; // Turnaround time
processes[idx].waiting = processes[idx].turnaround - processes[idx].burst; // Waiting time
completed++;
}
} else {
current_time++; // No process is ready, just increment time
}
}
// Calculate and display final times
calculateTimes(processes, n);
// Print the process details
printf("\nProcess ID\tBurst Time\tWaiting Time\tTurnaround Time\n");
for (int i = 0; i < n; i++) {
printf("%d\t\t%d\t\t%d\t\t%d\n",
processes[i].id, processes[i].burst,
processes[i].waiting, processes[i].turnaround);
}
return 0;
}