Service
Service
1) Write a program in C or C++ to implement the First Come First Service (FCFS) CPU
scheduling
#include <iostream>
#include <vector>
#include <iomanip>
#include <algorithm>
struct Process {
int pid;
int arrivalTime;
int burstTime;
int startTime;
int completionTime;
int turnaroundTime;
int waitingTime;
};
int main() {
int n;
cout << "Enter number of processes: ";
cin >> n;
vector<Process> p(n);
int currentTime = 0;
float totalWaitingTime = 0, totalTurnaroundTime = 0;
vector<string> ganttLabels;
vector<int> ganttTimes;
p[i].startTime = currentTime;
p[i].completionTime = currentTime + p[i].burstTime;
p[i].turnaroundTime = p[i].completionTime - p[i].arrivalTime;
p[i].waitingTime = p[i].turnaroundTime - p[i].burstTime;
totalWaitingTime += p[i].waitingTime;
totalTurnaroundTime += p[i].turnaroundTime;
ganttLabels.push_back("P" + to_string(p[i].pid));
ganttTimes.push_back(p[i].completionTime);
currentTime = p[i].completionTime;
}
// Output
cout << "\nProcess\tArrival\tBurst\tStart\tCompletion\tWaiting\tTurnaround\n";
for (auto &proc : p) {
cout << "P" << proc.pid << "\t" << proc.arrivalTime << "\t" <<
proc.burstTime << "\t"
<< proc.startTime << "\t" << proc.completionTime << "\t"
<< proc.waitingTime << "\t" << proc.turnaroundTime << "\n";
}
// Gantt Chart
cout << "\nGantt Chart:\n";
// Top bar
for (auto &label : ganttLabels) {
cout << " ";
for (int i = 0; i < label.length() + 2; i++) cout << "-";
}
cout << "\n|";
// Process labels
for (auto &label : ganttLabels) {
cout << " " << label << " |";
}
// Bottom bar
cout << "\n";
for (auto &label : ganttLabels) {
cout << " ";
for (int i = 0; i < label.length() + 2; i++) cout << "-";
}
// Time line
cout << "\n" << setw(2) << setfill(' ') << (p[0].startTime < p[0].arrivalTime ?
p[0].arrivalTime : p[0].startTime);
for (auto &time : ganttTimes) {
cout << setw(5) << time;
}
cout << "\n";
return 0;
}
2) Write a program in C or C++ to implement the Non-Preemptive Shortest Job First
(SJF) CPU
scheduling algorithm. Find the average Trun-Around Time (TAT) and average Waiting
Time
(WT). Your program will work for at least 10 processes.
#include <stdio.h>
struct Process {
int pid;
int burst_time;
int arrival_time;
int waiting_time;
int turnaround_time;
int completed;
int start_time;
};
int main() {
int n = 4;
struct Process p[20];
sort_by_arrival_time(p, n);
printf("\nGantt Chart:\n");
printf("--------------------------------------------------\n");
while(completed < n) {
int idx = -1;
int min_bt = 1e9;
if(idx != -1) {
p[idx].start_time = current_time;
p[idx].waiting_time = current_time - p[idx].arrival_time;
p[idx].turnaround_time = p[idx].waiting_time + p[idx].burst_time;
current_time += p[idx].burst_time;
p[idx].completed = 1;
completed++;
total_waiting_time += p[idx].waiting_time;
total_turnaround_time += p[idx].turnaround_time;
} else {
current_time++; // CPU idle
}
}
printf("|\n--------------------------------------------------\n");
printf("\nPID\tAT\tBT\tWT\tTAT\n");
for(int i=0; i<n; i++) {
printf("%d\t%d\t%d\t%d\t%d\n", p[i].pid, p[i].arrival_time,
p[i].burst_time, p[i].waiting_time, p[i].turnaround_time);
}
return 0;
}
ass2
struct Process {
int pid;
int arrival_time;
int burst_time;
int priority;
int waiting_time;
int turnaround_time;
int start_time;
bool completed = false;
};
int main() {
int n = 5;
vector<Process> processes(n);
cout << "Enter Arrival Time, Burst Time and Priority (Lower number = Higher
priority):\n";
for(int i = 0; i < n; ++i) {
processes[i].pid = i + 1;
cout << "Process " << i+1 << ":\n";
cout << "Arrival Time: ";
cin >> processes[i].arrival_time;
cout << "Burst Time: ";
cin >> processes[i].burst_time;
cout << "Priority: ";
cin >> processes[i].priority;
}
while(completed < n) {
int idx = -1;
int highest_priority = 1e9;
if(idx != -1) {
Process &p = processes[idx];
p.start_time = current_time;
p.waiting_time = current_time - p.arrival_time;
p.turnaround_time = p.waiting_time + p.burst_time;
current_time += p.burst_time;
p.completed = true;
completed++;
total_wt += p.waiting_time;
total_tat += p.turnaround_time;
cout << "| P" << p.pid << " (" << p.start_time << "-" << current_time
<< ") ";
} else {
current_time++; // CPU Idle
}
}
return 0;
}
2) Write a program in C or C++ to implement the primitive sjf. find the avg tat,
wt.
#include <iostream>
#include <vector>
using namespace std;
struct Process {
int pid;
int arrival_time;
int burst_time;
int remaining_time;
int completion_time;
int waiting_time;
int turnaround_time;
};
int main() {
int n = 3;
vector<Process> processes(n);
while(completed < n) {
int idx = -1, min_rt = 1e9;
for(int i = 0; i < n; ++i) {
if(processes[i].arrival_time <= current_time &&
processes[i].remaining_time > 0) {
if(processes[i].remaining_time < min_rt) {
min_rt = processes[i].remaining_time;
idx = i;
}
}
}
if(idx != -1) {
processes[idx].remaining_time--;
cout << "|P" << processes[idx].pid << "(" << current_time << "-" <<
current_time+1 << ")";
if(processes[idx].remaining_time == 0) {
completed++;
processes[idx].completion_time = current_time + 1;
processes[idx].turnaround_time = processes[idx].completion_time -
processes[idx].arrival_time;
processes[idx].waiting_time = processes[idx].turnaround_time -
processes[idx].burst_time;
total_wt += processes[idx].waiting_time;
total_tat += processes[idx].turnaround_time;
}
} else {
cout << "|Idle(" << current_time << "-" << current_time+1 << ")";
}
current_time++;
}
return 0;
}
as3
struct GanttEntry {
int pid, start, end;
};
int main() {
int n;
cout << "Enter number of processes (>=10): ";
cin >> n;
if (idx == -1) {
// CPU idle
time++;
continue;
}
// Preemption detection
if (last_pid != -1 && last_pid != idx && rem_bt[last_pid] > 0)
preempt_count[last_pid]++;
// Record Gantt
if (gantt.empty() || gantt.back().pid != idx) {
gantt.push_back({idx, time, time+1});
} else {
gantt.back().end++;
}
last_pid = idx;
// Execute one time unit
rem_bt[idx]--;
time++;
// If process completes
if (rem_bt[idx] == 0) {
completed++;
ct[idx] = time;
tat[idx] = ct[idx] - at[idx];
wt[idx] = tat[idx] - bt[idx];
}
}
// Output table
double sumTAT = 0, sumWT = 0;
cout << "\nPID\tAT\tBT\tPR\tCT\tTAT\tWT\tPreemptions\n";
for (int i = 0; i < n; i++) {
cout << i+1 << "\t"
<< at[i] << "\t"
<< bt[i] << "\t"
<< pr[i] << "\t"
<< ct[i] << "\t"
<< tat[i] << "\t"
<< wt[i] << "\t"
<< preempt_count[i] << "\n";
sumTAT += tat[i];
sumWT += wt[i];
}
return 0;
}
"Write a C++ function to implement Round Robin scheduling for a set of processes
with a given time quantum."
#include <iostream>
#include <queue>
#include <vector>
#include <iomanip>
#include <algorithm>
struct Process {
int pid; // Process ID
int arrival_time; // Arrival Time
int burst_time; // Burst Time
int remaining_time; // Remaining Burst Time
int completion_time;// Completion Time
int waiting_time; // Waiting Time
int turnaround_time;// Turnaround Time
int preemptions; // Number of Preemptions
int last_executed; // Last time the process was executed
};
struct GanttChartEntry {
int pid;
int start_time;
int end_time;
};
int main() {
int n, time_quantum;
cout << "Enter the number of processes: ";
cin >> n;
vector<Process> processes(n);
roundRobinScheduling(processes, time_quantum);
return 0;
}
Assignment 4
1) Write a program in C or C++ to implement the multilevel feedback queue cpu
scheduling algo.find the avg tat,wt.
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
struct Process
{
int id, at, bt, remaning_bt, ct = 0, tat = 0, wt = 0, preemptions = 0;
};
int main()
{
int n;
cout << "Enter number of processes: ";
cin >> n;
int timeQuantum1, timeQuantum2, timeQuantum3;
cout << "Enter the time Quantum: ";
cin >> timeQuantum1 >> timeQuantum2 >> timeQuantum3;
vector<Process> processes(n);
for (int i = 0; i < n; i++)
{
cout << "Enter Arrival Time and Burst Time for process " << i + 1 << ": ";
cin >> processes[i].at >> processes[i].bt;
processes[i].id = i + 1;
processes[i].remaning_bt = processes[i].bt;
}
sort(processes.begin(), processes.end(), comp);
// once these three rrScheduling runs we will be left with a Q4 containing the
process that are still not completed
// now we have to just do a fcfs
while (!Q4.empty())
{
int i = Q4.front() - 1;
currentTime += processes[i].remaning_bt;
processes[i].remaning_bt = 0;
gantt_chart.emplace_back(processes[i].id, currentTime);
Q4.pop();
}
// sorted the processes again to bascially make the output look good
sort(processes.begin(), processes.end(), compid);
Assignment 5
1) Write a program in C or C++ to implement the multilevel queue cpu scheduling
having 5 queues system interactive editing, batch and student processes from high
priority to low.
find the avg tat,wt. count the no of premption takes place during the arrival of a
low priority process.
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
struct Process {
int id;
int arrival;
int burst;
int remaining;
int priority;
int start = -1;
int finish = 0;
int waiting = 0;
int turnaround = 0;
bool completed = false;
};
int main() {
int n;
cout << "Enter number of processes: ";
cin >> n;
vector<Process> processes(n);
for (int i = 0; i < n; i++) {
cout << "\nProcess " << i + 1 << ":\n";
processes[i].id = i + 1;
cout << "Arrival Time: ";
cin >> processes[i].arrival;
cout << "Burst Time: ";
cin >> processes[i].burst;
processes[i].remaining = processes[i].burst;
cout << "Queue (1-5) [1=High, 5=Low]: ";
cin >> processes[i].priority;
}
vector<queue<Process*>> queues(5);
int time = 0, completed = 0, preemptions = 0;
Process* current = nullptr;
if (current != nullptr) {
if (current->start == -1)
current->start = time;
current->remaining--;
if (current->remaining == 0) {
current->finish = time + 1;
current->turnaround = current->finish - current->arrival;
current->waiting = current->turnaround - current->burst;
current->completed = true;
completed++;
current = nullptr;
}
}
time++;
}
// Output
double totalTAT = 0, totalWT = 0;
cout << "\nID\tArrival\tBurst\tQueue\tTAT\tWT\n";
for (auto &p : processes) {
totalTAT += p.turnaround;
totalWT += p.waiting;
cout << p.id << "\t" << p.arrival << "\t" << p.burst << "\t"
<< p.priority << "\t" << p.turnaround << "\t" << p.waiting << endl;
}
return 0;
}
Assignment 6
1. Write a program in C to demonstrate the creation and termination of the child
process. Your program must include a series of system calls to create new child
processes and each child process must do the same function or task. Check if the
series contains "n" System calls, then
your program creates how many child processes and how many times the common task
will be executed.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
int n; // number of fork system calls
printf("Enter the number of fork system calls (n): ");
scanf("%d", &n);
int total_forks = n;
int i;
for (i = 0; i < total_forks; i++) {
pid_t pid = fork();
if (pid < 0) {
perror("fork failed");
exit(1);
} else if (pid == 0) {
// Child process
common_task();
exit(0); // Important to prevent child from creating more children
}
// Parent process waits for the child
wait(NULL);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid1, pid2;
pid1 = fork();
if (pid1 < 0) {
perror("fork failed");
exit(1);
} else if (pid1 == 0) {
// First child process: factorization
printf("Child 1 (PID: %d): ", getpid());
factorize(28);
exit(0);
} else {
pid2 = fork();
if (pid2 < 0) {
perror("fork failed");
exit(1);
} else if (pid2 == 0) {
// Second child process: GCD
int a = 60, b = 48;
printf("Child 2 (PID: %d): GCD of %d and %d is %d\n", getpid(), a, b,
gcd(a, b));
exit(0);
} else {
// Parent process waits for both children
wait(NULL);
wait(NULL);
printf("Parent (PID: %d): Both child processes completed.\n",
getpid());
}
}
return 0;
}
Assignment 7
1. Write a program to implement Deadlock Prevention Using Banker’s Algorithm.
#include <stdio.h>
#define MAX_PROCESSES 10
#define MAX_RESOURCES 10
int main() {
int n, m, i, j, k;
int alloc[MAX_PROCESSES][MAX_RESOURCES];
int max[MAX_PROCESSES][MAX_RESOURCES];
int need[MAX_PROCESSES][MAX_RESOURCES];
int avail[MAX_RESOURCES];
int finish[MAX_PROCESSES];
int safe_seq[MAX_PROCESSES];
// Safety algorithm
int count = 0;
while (count < n) {
int found = 0;
for (i = 0; i < n; i++) {
if (!finish[i]) {
// Check if need[i] <= avail
for (j = 0; j < m; j++)
if (need[i][j] > avail[j])
break;
if (j == m) {
// Simulate allocation
for (k = 0; k < m; k++)
avail[k] += alloc[i][k];
safe_seq[count++] = i;
finish[i] = 1;
found = 1;
}
}
}
if (!found) {
printf("System is NOT in a safe state.\n");
return 0;
}
}
#define MAX_PROCESSES 10
#define MAX_RESOURCES 10
int main() {
int n, m; // number of processes and resource types
int max[MAX_PROCESSES][MAX_RESOURCES]; // max resource need
int alloc[MAX_PROCESSES][MAX_RESOURCES] = {0}; // resources currently allocated
int avail[MAX_RESOURCES]; // available resources
bool finished[MAX_PROCESSES] = {false};
int completed = 0;
while (completed < n) {
bool allocated_this_round = false;
if (can_allocate) {
printf("Process P%d is allocated resources: ", i);
for (int j = 0; j < m; j++) {
avail[j] -= max[i][j];
alloc[i][j] = max[i][j];
printf("%d ", alloc[i][j]);
}
printf("\nProcess P%d is executing...\n", i);
if (!allocated_this_round) {
printf("No further allocation possible. System might be in unsafe
state.\n");
break;
}
}
if (completed == n) {
printf("All processes executed without Hold and Wait. System is safe.\n");
}
return 0;
}
return NULL;
}
int main() {
pthread_t threads[2];
thread_info_t infos[2] = {
{ .thread_id = 1, .needed_resources = {2, 0}, .count = 2 },
{ .thread_id = 2, .needed_resources = {1, 0}, .count = 2 }
};
// Create threads
for (int i = 0; i < 2; i++) {
pthread_create(&threads[i], NULL, thread_func, &infos[i]);
}
// Destroy mutexes
for (int i = 0; i < NUM_RESOURCES; i++) {
pthread_mutex_destroy(&resource_mutex[i]);
}
#include <stdio.h>
#include <stdbool.h>
#define MAX_PROCESSES 10
#define MAX_RESOURCES 10
int main() {
int n, m, i, j, p;
// Data structures
int priority[MAX_PROCESSES];
int max[MAX_PROCESSES][MAX_RESOURCES];
int alloc[MAX_PROCESSES][MAX_RESOURCES] = {0};
int avail[MAX_RESOURCES];
bool waiting[MAX_PROCESSES] = {false};
// Input counts
printf("Enter number of processes: ");
scanf("%d", &n);
printf("Enter number of resource types: ");
scanf("%d", &m);
int req[MAX_RESOURCES];
printf("Enter request vector for P%d:\n", p);
for (j = 0; j < m; j++)
scanf("%d", &req[j]);
if (!direct) {
// Preempt all lower-priority processes
for (i = 0; i < n; i++) {
if (!waiting[i] && priority[i] > priority[p]) {
printf("Preempting P%d (lower priority %d > %d)\n",
i, priority[i], priority[p]);
for (j = 0; j < m; j++) {
avail[j] += alloc[i][j];
alloc[i][j] = 0;
}
waiting[i] = true;
}
}
}
// Now allocate
bool ok = true;
for (j = 0; j < m; j++) {
if (req[j] > avail[j]) ok = false;
}
if (!ok) {
printf("Still insufficient resources after preemption. P%d must wait.\
n", p);
waiting[p] = true;
} else {
for (j = 0; j < m; j++) {
avail[j] -= req[j];
alloc[p][j] += req[j];
}
waiting[p] = false;
printf("Allocated to P%d. Available now: ", p);
for (j = 0; j < m; j++) printf("%d ", avail[j]);
printf("\n");
}
}
printf("Exiting.\n");
return 0;
}
pthread_mutex_lock(&mutex2);
printf("Thread %d acquired mutex2\n", id);
// Critical section
printf("Thread %d in critical section\n", id);
pthread_mutex_unlock(&mutex1);
printf("Thread %d released mutex1\n", id);
return NULL;
}
int main() {
pthread_t t1, t2;
int id1 = 1, id2 = 2;
return 0;
}
Assignment 8
1 Implementation and stimulation of MFT(multiple fixed partition algorithm)
algorithms.
//Q1: C Program to Implement and Simulate MFT (Multiple Fixed Partitioning)
#include <stdio.h>
#define MAX 10
int main() {
int partitionSize[10], memorySize, blockCount, processCount;
int processSize[10], allocation[10];
// Allocation
for (int i = 0; i < processCount; i++) {
for (int j = 0; j < blockCount; j++) {
if (partitionSize[j] >= processSize[i]) {
allocation[i] = j;
partitionSize[j] = -1; // Mark partition as used
break;
}
}
}
// Output
printf("\nProcess No\tProcess Size\tPartition Allocated\n");
for (int i = 0; i < processCount; i++) {
printf("%d\t\t%d\t\t", i + 1, processSize[i]);
if (allocation[i] != -1)
printf("%d\n", allocation[i] + 1);
else
printf("Not Allocated\n");
}
return 0;
}
#include <stdio.h>
int main() {
int memSize, remainingMem, processSize, processCount = 0, choice;
remainingMem = memSize;
do {
printf("\nEnter size of process %d: ", processCount + 1);
scanf("%d", &processSize);
printf("Do you want to add more processes? (1: Yes / 0: No): ");
scanf("%d", &choice);
} while (choice == 1);
return 0;
}
#define MAX 25
int main() {
int blockSize[MAX], processSize[MAX];
int blocks, processes, choice;
do {
int tempBlock[MAX];
memcpy(tempBlock, blockSize, blocks * sizeof(int)); // Reset block sizes
switch (choice) {
case 1:
firstFit(tempBlock, blocks, processSize, processes);
break;
case 2:
bestFit(tempBlock, blocks, processSize, processes);
break;
case 3:
worstFit(tempBlock, blocks, processSize, processes);
break;
case 4:
printf("Exiting...\n");
break;
default:
printf("Invalid choice!\n");
}
} while (choice != 4);
return 0;
}
// First Fit
void firstFit(int blockSize[], int blocks, int processSize[], int processes) {
int allocation[MAX];
memset(allocation, -1, sizeof(allocation));
// Best Fit
void bestFit(int blockSize[], int blocks, int processSize[], int processes) {
int allocation[MAX];
memset(allocation, -1, sizeof(allocation));
Assignment 9
1. wap to implement the fifo page replacement algo
// Q1: FIFO Page Replacement in C
#include <stdio.h>
int main() {
// Declare variables
int pages[50], frames[10];
// pages[] stores page reference string; frames[] stores memory frames
int n, f, i, j, k, flag, pageFaults = 0;
int pos = 0; // Tracks the position to insert the next page (FIFO queue)
printf("\nPage\tFrames\n");
int main() {
int n, f, i, j, pageFaults = 0;
int pages[100], frames[10];
printf("\nPage\tFrames\n");
// Page fault
if (!flag) {
int replaced = -1;
if (replaced == -1) {
int index = findOptimal(pages, frames, n, i + 1, f);
frames[index] = pages[i];
}
pageFaults++;
// Function to find the Least Recently Used (LRU) frame based on time[]
int findLRU(int time[], int n) {
int min = time[0], pos = 0;
for (int i = 1; i < n; i++) {
if (time[i] < min) {
min = time[i]; // find the smallest time value
pos = i; // position of the least recently used page
}
}
return pos; // return position to replace
}
int main() {
int n, f, i, j, pageFaults = 0;
int time[10], counter = 0; // time[] stores last used time for each frame
int pages[100], frames[10]; // pages[] is the reference string, frames[] is
memory
printf("\nPage\tFrames\n");
int main() {
int memSize, frameSize, numPages, i;
int pageTable[100];
int logicalAddr;
printf("\nEnter a logical address (page number and offset):\n");
int pageNum, offset;
scanf("%d %d", &pageNum, &offset);
return 0;
}
// Function to find the index of the Least Frequently Used (LFU) page
int findLFU(PageFrame frames[], int frameCount) {
int minFreq = frames[0].freq;
int pos = 0;
int main() {
int pages[MAX], n, frameCount;