0% found this document useful (0 votes)
61 views54 pages

Operating Systems Lab

The document is a practical record for an Operating Systems lab course. It contains details of the student such as name, enrollment number, semester etc. It then lists 13 programs that the student needs to complete as part of the lab assignments. For each program it lists the aim, theory and space to enter marks awarded by different evaluators.

Uploaded by

shivamcps6010
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)
61 views54 pages

Operating Systems Lab

The document is a practical record for an Operating Systems lab course. It contains details of the student such as name, enrollment number, semester etc. It then lists 13 programs that the student needs to complete as part of the lab assignments. For each program it lists the aim, theory and space to enter marks awarded by different evaluators.

Uploaded by

shivamcps6010
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/ 54

OPERATING SYSTEMS LAB

PAPER CODE (CIC-353)

Faculty Name: Student Name: Shivam Kaushik


Ms.Meenu Garg Enrollment No.: 07514803121
Assistant Professor Semester: 5th
Group: 5I4

Maharaja Agrasen Institute of Technology, PSP Area,


Sector – 22, Rohini, New Delhi – 110086
OPERATING SYSTEMS LAB
PRACTICAL RECORD

PAPER CODE : CIC-353

Name of the student : Shivam Kaushik

University Roll No. :07514803121

Branch : Information Technology

Section/ Group : 5I4

PRACTICAL DETAILS

Program Date Program Name Marks (0-3) Total Signature


No. Marks
(15)
R1 R2 R3 R4 R5
1. Introduction to Operating
Systems

2. Execution of various Linux


Commands

3. Write a program to
implement CPU scheduling
for first come first serve.
4. Write a program to
implement CPU scheduling
for shortest job first.
5. Write a program to
perform priority
scheduling.
6. Write a program to
implement CPU scheduling
for Round Robin.
7. Write a program for page
replacement policy using
a) LRU b) FIFO c)
Optimal
8. Write a program to
implement first fit, best fit
and worst fit algorithm for
memory management.
9. Write a program to
implement reader/writer
problem using semaphore.
10. Write a program to
implement producer-
consumer problem using
semaphores.
11. Write a program to
implement banker’s
algorithm for deadlock
avoidance.
12. Write C programs to
implement the various file
organization techniques.
PROGRAM – 1

AIM: Introduction to Operating Systems

THEORY:
PROGRAM – 2

AIM: Execution of various Linux Commands

THEORY:
PROGRAM – 3

AIM: Write a program to implement CPU scheduling for first come first serve

THEORY:
CODE:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Process {
int id;
int arrivalTime;
int burstTime;
int startTime;
int completionTime;
int turnaroundTime;
int waitingTime;
};
void nonPreemptiveFCFS(vector<Process>& processes) {
int currentTime = 0;
for (auto& process : processes) {
process.startTime = max(currentTime, process.arrivalTime);
process.completionTime = process.startTime + process.burstTime;
process.turnaroundTime = process.completionTime - process.arrivalTime;
process.waitingTime = process.turnaroundTime - process.burstTime;
currentTime = process.completionTime;
}
}
void preemptiveFCFS(vector<Process>& processes) {
int currentTime = 0;
for (auto& process : processes) {
process.startTime = max(currentTime, process.arrivalTime);
process.completionTime = process.startTime + process.burstTime;
process.turnaroundTime = process.completionTime - process.arrivalTime;
process.waitingTime = process.turnaroundTime - process.burstTime;
currentTime = process.completionTime;
}
}
void displayProcesses(const vector<Process>& processes) {
cout << "Process ID\tArrival Time\tBurst Time\tCompletion Time\tTurnaround
Time\tWaiting Time\n";
for (const auto& process : processes) {
cout << process.id << "\t\t" << process.arrivalTime << "\t\t" << process.burstTime <<
"\t\t"
<< process.completionTime << "\t\t" << process.turnaroundTime << "\t\t" <<
process.waitingTime << endl;
}
}
int main() {
int choice;
vector<Process> processes = {
{1, 0, 5, 0, 0, 0, 0},
{2, 2, 3, 0, 0, 0, 0},
{3, 4, 1, 0, 0, 0, 0},
{4, 6, 2, 0, 0, 0, 0},
{5, 8, 4, 0, 0, 0, 0}
};
cout << "Select scheduling type:\n";
cout << "1. Non-preemptive FCFS\n";
cout << "2. Preemptive FCFS\n";
cout << "Enter choice: ";
cin >> choice;
switch (choice) {
case 1:
nonPreemptiveFCFS(processes);
displayProcesses(processes);
break;
case 2:
preemptiveFCFS(processes);
displayProcesses(processes);
break;
default:
cout << "Invalid choice.\n";
break;
}
return 0;
}

OUTPUT:
PROGRAM – 4

AIM: Write a program to implement CPU scheduling for shortest job first

THEORY:
CODE:

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <climits> // Include the necessary
header using namespace std;
struct Process {
int id;
int arrivalTime;
int burstTime;
int startTime;
int completionTime;
int turnaroundTime;
int waitingTime;
int remainingTime; // For preemptive SJF
};
void nonPreemptiveSJF(vector<Process>& processes) {
sort(processes.begin(), processes.end(), [](const Process& a, const Process& b) {
return a.burstTime < b.burstTime || (a.burstTime == b.burstTime && a.arrivalTime <
b.arrivalTime);
});
int currentTime = 0;
for (auto& process : processes) {
process.startTime = max(currentTime, process.arrivalTime);
process.completionTime = process.startTime + process.burstTime;
process.turnaroundTime = process.completionTime - process.arrivalTime;
process.waitingTime = process.turnaroundTime - process.burstTime;
currentTime = process.completionTime;
}
}
void preemptiveSJF(vector<Process>& processes) {
sort(processes.begin(), processes.end(), [](const Process& a, const Process& b) {
return a.arrivalTime < b.arrivalTime;
});
int currentTime = 0;
int completed = 0;
vector<bool> executed(processes.size(), false);
while (completed < processes.size()) {
int shortest = -1;
int shortestBurst = INT_MAX;
for (int i = 0; i < processes.size(); ++i) {
if (processes[i].arrivalTime <= currentTime && !executed[i]
&& processes[i].burstTime < shortestBurst) {
shortest = i;
shortestBurst = processes[i].burstTime;
}
}
if (shortest == -1) {
currentTime++;
continue;
}
processes[shortest].startTime =
currentTime;
processes[shortest].burstTime--;
currentTime++;
if (processes[shortest].burstTime == 0) {
processes[shortest].completionTime = currentTime;
processes[shortest].turnaroundTime = processes[shortest].completionTime -
processes[shortest].arrivalTime;
processes[shortest].waitingTime = processes[shortest].turnaroundTime -
processes[shortest].remainingTime;
executed[shortest] = true;
completed++;
}
}
}
void displayProcesses(const vector<Process>& processes) {
cout << "Process ID\tArrival Time\tBurst Time\tCompletion Time\tTurnaround
Time\tWaiting Time\n";
for (const auto& process : processes) {
cout << process.id << "\t\t" << process.arrivalTime << "\t\t" << process.remainingTime
<< "\t\t"
<< process.completionTime << "\t\t" << process.turnaroundTime << "\t\t" <<
process.waitingTime << endl;
}
}
int main() {
int choice;
vector<Process> processes = {
{1, 0, 8, 0, 0, 0, 0, 8},
{2, 1, 4, 0, 0, 0, 0, 4},
{3, 2, 9, 0, 0, 0, 0, 9},
{4, 3, 5, 0, 0, 0, 0, 5},
{5, 4, 2, 0, 0, 0, 0, 2}
};
cout << "Select scheduling type:\n";
cout << "1. Non-preemptive SJF\n";
cout << "2. Preemptive SJF\n";
cout << "Enter choice:
"; cin >> choice;
switch (choice) {
case 1:
nonPreemptiveSJF(processes);
displayProcesses(processes);
break;
case 2:
preemptiveSJF(processes);
displayProcesses(processes);
break;
default:
cout << "Invalid choice.\n";
break;
}

return 0;
}

OUTPUT:
PROGRAM – 5

AIM: Write a program to perform priority scheduling

THEORY:
CODE:

#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
struct Process {
int id;
int arrivalTime;
int burstTime;
int priority;
int startTime;
int completionTime;
int turnaroundTime;
int waitingTime;
int remainingTime; // For preemptive Priority
};

void nonPreemptivePriority(vector<Process>& processes) {


sort(processes.begin(), processes.end(), [](const Process& a, const Process& b) {
return a.priority < b.priority || (a.priority == b.priority && a.arrivalTime <
b.arrivalTime);
});

int currentTime = 0;
for (auto& process : processes) {
process.startTime = max(currentTime, process.arrivalTime);
process.completionTime = process.startTime + process.burstTime;
process.turnaroundTime = process.completionTime - process.arrivalTime;
process.waitingTime = process.turnaroundTime - process.burstTime;
currentTime = process.completionTime;
}
}

void preemptivePriority(vector<Process>& processes) {


sort(processes.begin(), processes.end(), [](const Process& a, const Process& b) {
return a.arrivalTime < b.arrivalTime;
});

int currentTime = 0;
int completed = 0;
vector<bool> executed(processes.size(), false);
while (completed < processes.size()) {
int highestPriority = INT_MAX;
int highestPriorityIdx = -1;

for (int i = 0; i < processes.size(); ++i) {


if (processes[i].arrivalTime <= currentTime && !executed[i] && processes[i].priority
< highestPriority) {
highestPriority = processes[i].priority;
highestPriorityIdx = i;
}
}

if (highestPriorityIdx == -1) {
currentTime++;
continue;
}

processes[highestPriorityIdx].startTime =
currentTime;
processes[highestPriorityIdx].remainingTime--;
currentTime++;

if (processes[highestPriorityIdx].remainingTime == 0) {
processes[highestPriorityIdx].completionTime = currentTime;
processes[highestPriorityIdx].turnaroundTime =
processes[highestPriorityIdx].completionTime - processes[highestPriorityIdx].arrivalTime;
processes[highestPriorityIdx].waitingTime =
processes[highestPriorityIdx].turnaroundTime - processes[highestPriorityIdx].burstTime;
executed[highestPriorityIdx] = true;
completed++;
}
}
}

void displayProcesses(const vector<Process>& processes) {


cout << "Process ID\tArrival Time\tBurst Time\tPriority\tCompletion Time\tTurnaround
Time\tWaiting Time\n";
for (const auto& process : processes) {
cout << process.id << "\t\t" << process.arrivalTime << "\t\t" << process.burstTime <<
"\t\t"
<< process.priority << "\t\t" << process.completionTime << "\t\t" <<
process.turnaroundTime << "\t\t"
<< process.waitingTime << endl;
}
}

int main() {
int choice;
vector<Process> processes = {
{1, 0, 8, 3, 0, 0, 0, 0, 8},
{2, 1, 4, 1, 0, 0, 0, 0, 4},
{3, 2, 9, 2, 0, 0, 0, 0, 9},
{4, 3, 5, 4, 0, 0, 0, 0, 5},
{5, 4, 2, 5, 0, 0, 0, 0, 2}
};

cout << "Select scheduling type:\n";


cout << "1. Non-preemptive Priority\n";
cout << "2. Preemptive Priority\n";
cout << "Enter choice: ";
cin >> choice;

switch (choice) {
case 1:
nonPreemptivePriority(processes);
displayProcesses(processes);
break;
case 2:
preemptivePriority(processes);
displayProcesses(processes);
break;
default:
cout << "Invalid choice.\n";
break;
}

return 0;
}

OUTPUT:
PROGRAM – 6

AIM: Write a program to implement CPU Scheduling for Round Robin

THEORY:
CODE:

#include<iostream>
using namespace std;
// Function to find the waiting time for all
// processes
void findWaitingTime(int processes[], int n,
int bt[], int wt[], int quantum)
{
// Make a copy of burst times bt[] to store remaining
// burst times.
int rem_bt[n];
for (int i = 0 ; i < n ; i++)
rem_bt[i] = bt[i];

int t = 0; // Current time

// Keep traversing processes in round robin manner


// until all of them are not done.
while (1)
{
bool done = true;

// Traverse all processes one by one


repeatedly for (int i = 0 ; i < n; i++)
{
// If burst time of a process is greater than 0
// then only need to process
further if (rem_bt[i] > 0)
{
done = false; // There is a pending process

if (rem_bt[i] > quantum)


{
// Increase the value of t i.e. shows
// how much time a process has been processed
t += quantum;

// Decrease the burst_time of current process


// by quantum
rem_bt[i] -= quantum;
}

// If burst time is smaller than or equal to


// quantum. Last cycle for this process
else
{
// Increase the value of t i.e. shows
// how much time a process has been processed
t = t + rem_bt[i];
// Waiting time is current time minus time
// used by this process
wt[i] = t - bt[i];

// As the process gets fully executed


// make its remaining burst time = 0
rem_bt[i] = 0;
}
}
}

// If all processes are done


if (done == true)
break;
}
}

// Function to calculate turn around time


void findTurnAroundTime(int processes[], int n,
int bt[], int wt[], int tat[])
{
// calculating turnaround time by adding
// bt[i] + wt[i]
for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i];
}

// Function to calculate average time


void findavgTime(int processes[], int n, int bt[],
int quantum)
{
int wt[n], tat[n], total_wt = 0, total_tat = 0;

// Function to find waiting time of all processes


findWaitingTime(processes, n, bt, wt, quantum);

// Function to find turn around time for all


processes findTurnAroundTime(processes, n, bt,
wt, tat);

// Display processes along with all details


cout << "PN\t "<< " \tBT "
<< " WT " << " \tTAT\n";

// Calculate total waiting time and total turn


// around time
for (int i=0; i<n; i++)
{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
cout << " " << i+1 << "\t\t" << bt[i] <<"\t "
<< wt[i] <<"\t\t " << tat[i] <<endl;
}

cout << "Average waiting time = "


<< (float)total_wt / (float)n;
cout << "\nAverage turn around time = "
<< (float)total_tat / (float)n;
}

// Driver code
int main()
{
// process id's
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];

// Burst time of all processes


int burst_time[] = {10, 5, 8};

// Time quantum
int quantum = 2;
findavgTime(processes, n, burst_time, quantum);
return 0;
}

OUTPUT:
PROGRAM – 7 (a)

AIM: Write a program for page replacement policy using LRU

THEORY:
CODE:

#include<bits/stdc++.h>
using namespace std;

// Function to find page faults using indexes

int pageFaults(int pages[], int n, int capacity)

{
// To represent set of current pages. We use
// an unordered_set so that we quickly check
// if a page is present in set or not
unordered_set<int> s;
// To store least recently used indexes
// of pages.
unordered_map<int, int> indexes;
// Start from initial page
int page_faults = 0;
for (int i=0; i<n; i++) {
// Check if the set can hold more
pages if (s.size() < capacity) {
// Insert it into set if not present
// already which represents page
fault if (s.find(pages[i])==s.end())
{
s.insert(pages[i]);

// increment page fault


page_faults++;
}
// Store the recently used index of
// each page
indexes[pages[i]] = i;
}

// If the set is full then need to perform lru


// i.e. remove the least recently used page
// and insert the current page

else{
// Check if current page is not already
// present in the set
if (s.find(pages[i]) == s.end()) {
// Find the least recently used pages
// that is present in the set
int lru = INT_MAX, val;
for (auto it=s.begin(); it!=s.end(); it++) {
if (indexes[*it] < lru) {
lru = indexes[*it];
val = *it;
}
}

// Remove the indexes page


s.erase(val);
// insert the current page
s.insert(pages[i]);
// Increment page faults
page_faults++;
}
// Update the current page index
indexes[pages[i]] = i;
}
}

return page_faults;
}

// Driver code

int main()
{
int pages[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};
int n = sizeof(pages)/sizeof(pages[0]);
int capacity = 4;
cout << pageFaults(pages, n, capacity);
return 0;
}

OUTPUT:
PROGRAM – 7 (b)

AIM: Write a program for page replacement policy using FIFO

THEORY:
CODE:

// C++ implementation of FIFO page replacement


// in Operating Systems.
#include<bits/stdc++.h>
using namespace std;

// Function to find page faults using FIFO


int pageFaults(int pages[], int n, int
capacity)
{
// To represent set of current pages. We use
// an unordered_set so that we quickly check
// if a page is present in set or not
unordered_set<int> s;

// To store the pages in FIFO manner


queue<int> indexes;

// Start from initial page


int page_faults = 0;
for (int i=0; i<n; i++)
{
// Check if the set can hold more
pages if (s.size() < capacity)
{
// Insert it into set if not present
// already which represents page
fault if (s.find(pages[i])==s.end())
{
// Insert the current page into the set
s.insert(pages[i]);

// increment page fault


page_faults++;

// Push the current page into the queue


indexes.push(pages[i]);
}
}

// If the set is full then need to perform FIFO


// i.e. remove the first page of the queue from
// set and queue both and insert the current
page else
{
// Check if current page is not already
// present in the set
if (s.find(pages[i]) == s.end())
{
// Store the first page in the
// queue to be used to find and
// erase the page from the set
int val = indexes.front();

// Pop the first page from the queue


indexes.pop();

// Remove the indexes page from the set


s.erase(val);

// insert the current page in the set


s.insert(pages[i]);

// push the current page into


// the queue
indexes.push(pages[i]);

// Increment page faults


page_faults++;
}
}
}

return page_faults;
}

// Driver code
int main()
{
int pages[] = {7, 0, 1, 2, 0, 3, 0, 4,
2, 3, 0, 3, 2};
int n = sizeof(pages)/sizeof(pages[0]);
int capacity = 4;
cout << pageFaults(pages, n, capacity);
return 0;
}

OUTPUT:
PROGRAM – 7 (c)

AIM: Write a program for page replacement policy using Optimal Approach

THEORY:
CODE:

// CPP program to demonstrate optimal page


// replacement
algorithm. #include
<bits/stdc++.h> using
namespace std;

// Function to check whether a page exists


// in a frame or not
bool search(int key, vector<int>& fr)
{
for (int i = 0; i < fr.size(); i+
+) if (fr[i] == key)
return true;
return false;
}
// Function to find the frame that will not be used
// recently in future after given index in pg[0..pn-1]
int predict(int pg[], vector<int>& fr, int pn, int index){
// Store the index of pages which are going
// to be used recently in future
int res = -1, farthest = index;
for (int i = 0; i < fr.size(); i++) {
int j;
for (j = index; j < pn; j++) {
if (fr[i] == pg[j]) {
if (j > farthest) {
farthest = j;
res = i;
}
break;
}
}
// If a page is never referenced in future,
// return it.
if (j == pn)
return i;
}
// If all of the frames were not in future,
// return any of them, we return 0. Otherwise
// we return res.
return (res == -1) ? 0 : res;
}

void optimalPage(int pg[], int pn, int fn){


// Create an array for given number of
// frames and initialize it as empty.
vector<int> fr;
// Traverse through page reference array
// and check for miss and hit.
int hit = 0;
for (int i = 0; i < pn; i++) {
// Page found in a frame : HIT
if (search(pg[i], fr)) {
hit++;
continue;
}
// Page not found in a frame : MISS
// If there is space available in frames.
if (fr.size() < fn)
fr.push_back(pg[i]);

// Find the page to be replaced.


else {
int j = predict(pg, fr, pn, i + 1);
fr[j] = pg[i];
}
}
cout << "No. of hits = " << hit << endl;
cout << "No. of misses = " << pn - hit << endl;
}

// Driver Function
int main()
{
int pg[] = { 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2 };
int pn = sizeof(pg) / sizeof(pg[0]);
int fn = 4;
optimalPage(pg, pn, fn);
return 0;
}

OUTPUT:
PROGRAM – 8

AIM: Write a program to implement first fit, best fit and worst fit algorithm for
memory management

THEORY:
(A) FIRST FIT

CODE:

// C++ implementation of First - Fit algorithm


#include<bits/stdc++.h>
using namespace std;

// Function to allocate memory to


// blocks as per First fit algorithm
void firstFit(int blockSize[], int m,
int processSize[], int n)
{
// Stores block id of the
// block allocated to a process
int allocation[n];

// Initially no block is assigned to any process


memset(allocation, -1, sizeof(allocation));

// pick each process and find suitable blocks


// according to its size ad assign to it
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (blockSize[j] >= processSize[i])
{
// allocate block j to p[i] process
allocation[i] = j;

// Reduce available memory in this


block. blockSize[j] -= processSize[i];

break;
}
}
}

cout << "\nProcess No.\tProcess Size\tBlock no.\n";


for (int i = 0; i < n; i++)
{
cout << " " << i+1 << "\t\t"
<< processSize[i] << "\t\t";
if (allocation[i] != -1)
cout << allocation[i] + 1;
else
cout << "Not Allocated";
cout << endl;
}
}

// Driver code
int main()
{
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
int m = sizeof(blockSize) / sizeof(blockSize[0]);
int n = sizeof(processSize) /
sizeof(processSize[0]);

firstFit(blockSize, m, processSize, n);

return 0 ;
}

OUTPUT:
(B) BEST FIT

CODE:

// C++ implementation of Best - Fit algorithm


#include<iostream>
using namespace std;

// Method to allocate memory to blocks as per Best fit algorithm


void bestFit(int blockSize[], int m, int processSize[], int n)
{
// Stores block id of the block allocated to a
process int allocation[n];

// Initially no block is assigned to any process


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

// pick each process and find suitable blocks


// according to its size ad assign to it
for (int i = 0; i < n; i++)
{
// Find the best fit block for current
process int bestIdx = -1;
for (int j = 0; j < m; j++)
{
if (blockSize[j] >= processSize[i])
{
if (bestIdx == -1)
bestIdx = j;
else if (blockSize[bestIdx] >
blockSize[j]) bestIdx = j;
}
}

// If we could find a block for current process


if (bestIdx != -1)
{
// allocate block j to p[i] process
allocation[i] = bestIdx;

// Reduce available memory in this


block. blockSize[bestIdx] -=
processSize[i];
}
}

cout << "\nProcess No.\tProcess Size\tBlock no.\n";


for (int i = 0; i < n; i++)
{
cout << " " << i+1 << "\t\t" << processSize[i] << "\t\t";
if (allocation[i] != -1)
cout << allocation[i] + 1;
else
cout << "Not Allocated";
cout << endl;
}
}

// Driver Method
int main()
{
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
int m = sizeof(blockSize) / sizeof(blockSize[0]);
int n = sizeof(processSize) /
sizeof(processSize[0]);

bestFit(blockSize, m, processSize, n);

return 0 ;
}

OUTPUT:
(C) WORST FIT

CODE:

// C++ implementation of worst - Fit algorithm


#include<bits/stdc++.h>
using namespace std;

// Function to allocate memory to blocks as per worst fit


// algorithm
void worstFit(int blockSize[], int m, int processSize[],
int
n)
{
// Stores block id of the block allocated to a
// process
int allocation[n];

// Initially no block is assigned to any process


memset(allocation, -1, sizeof(allocation));

// pick each process and find suitable blocks


// according to its size ad assign to it
for (int i=0; i<n; i++)
{
// Find the best fit block for current
process int wstIdx = -1;
for (int j=0; j<m; j++)
{
if (blockSize[j] >= processSize[i])
{
if (wstIdx == -1)
wstIdx = j;
else if (blockSize[wstIdx] < blockSize[j])
wstIdx = j;
}
}

// If we could find a block for current process


if (wstIdx != -1)
{
// allocate block j to p[i] process
allocation[i] = wstIdx;

// Reduce available memory in this


block. blockSize[wstIdx] -=
processSize[i];
}
}

cout << "\nProcess No.\tProcess Size\tBlock no.\n";


for (int i = 0; i < n; i++)
{
cout << " " << i+1 << "\t\t" << processSize[i] << "\t\t";
if (allocation[i] != -1)
cout << allocation[i] + 1;
else
cout << "Not Allocated";
cout << endl;
}
}

// Driver code
int main()
{
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
int m = sizeof(blockSize)/sizeof(blockSize[0]);
int n = sizeof(processSize)/sizeof(processSize[0]);

worstFit(blockSize, m, processSize, n);

return 0 ;
}

OUTPUT:
PROGRAM – 9

AIM: Write a program to implement reader/writer problem using semaphores

THEORY:
CODE:

#include<semaphore.h>
#include<stdio.h>
#include<pthread.h>
# include<bits/stdc++.h>
using namespace std;
void *reader(void *);
void *writer(void *);
int readcount=0,writecount=0,sh_var=5,bsize[5];
sem_t x,y,z,rsem,wsem;
pthread_t r[3],w[2];
void *reader(void *i){
cout << "\n------------------------";
cout << "\n\n reader-" << i << " is reading";
sem_wait(&z);
sem_wait(&rsem);
sem_wait(&x);
readcount++;
if(readcount==1)
sem_wait(&wsem);
sem_post(&x);
sem_post(&rsem);
sem_post(&z);
cout << "\nupdated value :" << sh_var;
sem_wait(&x);
readcount--;
if(readcount==0)
sem_post(&wsem);
sem_post(&x);
}

void *writer(void *i){


cout << "\n\n writer-" << i << "is writing";
sem_wait(&y);
writecount++;
if(writecount==1)
sem_wait(&rsem);
sem_post(&y);
sem_wait(&wsem);

sh_var=sh_var+5;
sem_post(&wsem);
sem_wait(&y);
writecount--;
if(writecount==0)
sem_post(&rsem);
sem_post(&y);
}
int main(){
sem_init(&x,0,1);
sem_init(&wsem,0,1);
sem_init(&y,0,1);
sem_init(&z,0,1);
sem_init(&rsem,0,1);
pthread_create(&r[0],NULL,(void *)reader,(void *)0);
pthread_create(&w[0],NULL,(void *)writer,(void
*)0); pthread_create(&r[1],NULL,(void *)reader,(void
*)1); pthread_create(&r[2],NULL,(void *)reader,(void
*)2); pthread_create(&r[3],NULL,(void *)reader,(void
*)3); pthread_create(&w[1],NULL,(void *)writer,
(void *)3); pthread_create(&r[4],NULL,(void *)reader,
(void *)4); pthread_join(r[0],NULL);
pthread_join(w[0],NULL);
pthread_join(r[1],NULL);
pthread_join(r[2],NULL);
pthread_join(r[3],NULL);
pthread_join(w[1],NULL);
pthread_join(r[4],NULL);

return(0);
}

OUTPUT:
PROGRAM – 10

AIM: Write a program to implement Producer-Consumer problem using semaphores

THEORY:
CODE:

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>

const int BUFFER_SIZE = 5; // Size of the shared buffer

std::queue<int> buffer; // Shared buffer


std::mutex mtx; // Mutex to protect shared data
std::condition_variable bufferNotEmpty, bufferNotFull; // Condition variables
int itemCount = 0; // Count of items in the buffer

// Function prototypes
void producer(int id);
void consumer(int
id);

int main() {
// Create producer and consumer threads
std::thread producerThread(producer, 1);
std::thread consumerThread(consumer, 1);

// Join threads with the main thread


producerThread.join();
consumerThread.join();

return 0;
}

// Producer function
void producer(int id) {
for (int i = 0; i < 10; ++i) {
std::unique_lock<std::mutex> lock(mtx);

// Wait if the buffer is full


bufferNotFull.wait(lock, [] { return itemCount < BUFFER_SIZE; });

// Produce an item and add it to the


buffer int item = i + 1;
buffer.push(item);
++itemCount;
std::cout << "Producer " << id << " produced item " << item << std::endl;

// Notify consumers that the buffer is not


empty bufferNotEmpty.notify_all();

lock.unlock();
// Simulate some work being done by the producer
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
}

// Consumer function
void consumer(int id) {
for (int i = 0; i < 10; ++i) {
std::unique_lock<std::mutex> lock(mtx);

// Wait if the buffer is empty


bufferNotEmpty.wait(lock, [] { return itemCount > 0; });

// Consume an item from the buffer


int item = buffer.front();
buffer.pop();
--itemCount;
std::cout << "Consumer " << id << " consumed item " << item << std::endl;

// Notify producers that the buffer is not full


bufferNotFull.notify_all();

lock.unlock();

// Simulate some work being done by the consumer


std::this_thread::sleep_for(std::chrono::milliseconds(300));
}
}

OUTPUT:
PROGRAM – 11

AIM: Write a program to implement Banker’s Algorithm for Deadlock Avoidance

THEORY:
CODE:

// Banker's Algorithm
#include <iostream>
using namespace std;

int main()
{
// P0, P1, P2, P3, P4 are the Process names here

int n, m, i, j, k;
n = 5; // Number of processes
m = 3; // Number of resources
int alloc[5][3] = { { 0, 1, 0 }, // P0 // Allocation Matrix
{ 2, 0, 0 }, // P1
{ 3, 0, 2 }, // P2
{ 2, 1, 1 }, // P3
{ 0, 0, 2 } }; // P4

int max[5][3] = { { 7, 5, 3 }, // P0 // MAX Matrix


{ 3, 2, 2 }, // P1
{ 9, 0, 2 }, // P2
{ 2, 2, 2 }, // P3
{ 4, 3, 3 } }; // P4

int avail[3] = { 3, 3, 2 }; // Available Resources

int f[n], ans[n], ind = 0;


for (k = 0; k < n; k++) {
f[k] = 0;
}
int need[n][m];
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++)
need[i][j] = max[i][j] - alloc[i][j];
}
int y = 0;
for (k = 0; k < 5; k++) {
for (i = 0; i < n; i++) {
if (f[i] == 0) {

int flag = 0;
for (j = 0; j < m; j++) {
if (need[i][j] > avail[j]){
flag = 1;
break;
}
}

if (flag == 0) {
ans[ind++] = i;
for (y = 0; y < m; y++)
avail[y] += alloc[i][y];
f[i] = 1;
}
}
}
}

int flag = 1;

// To check if sequence is safe or not


for(int i = 0;i<n;i++)
{
if(f[i]==0)
{
flag = 0;
cout << "The given sequence is not safe";
break;
}
}

if(flag==1)
{
cout << "Following is the SAFE Sequence" <<
endl; for (i = 0; i < n - 1; i++)
cout << " P" << ans[i] << " ->";
cout << " P" << ans[n - 1] <<endl;
}

return (0);
}

OUTPUT:
PROGRAM – 12

AIM: Write C programs to implement the various File Organization Techniques

THEORY:
(A) SINGLE LEVEL DIRECTORY

ORGANIZATION CODE:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_FILES 100
#define MAX_FILENAME 20
struct File {
char filename[MAX_FILENAME];
// You can add more attributes to the file structure if needed
};
struct Directory {
struct File files[MAX_FILES];
int numFiles;
};
void initializeDirectory(struct Directory *dir)
{ dir->numFiles = 0;
}
void addFile(struct Directory *dir, const char *filename)
{ if (dir->numFiles < MAX_FILES) {
strncpy(dir->files[dir->numFiles].filename, filename, MAX_FILENAME - 1);
dir->files[dir->numFiles].filename[MAX_FILENAME - 1] = '\0';
dir->numFiles++;
printf("File '%s' added successfully.\n", filename);
} else {
printf("Directory is full. Cannot add file '%s'.\n", filename);
}
}
void listFiles(struct Directory *dir) {
printf("Files in the directory:\n");
for (int i = 0; i < dir->numFiles; i++) {
printf("%s\n", dir->files[i].filename);
}
}
int main() {
struct Directory myDirectory;
initializeDirectory(&myDirectory);
int choice;
char filename[MAX_FILENAME];
do {
printf("\n1. Add File\n");
printf("2. List Files\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the filename: ");
scanf("%s", filename);
addFile(&myDirectory, filename);
break;
case 2:
listFiles(&myDirectory);
break;
case 3:
printf("Exiting the program.\n");
break;
default:
printf("Invalid choice. Please enter a valid option.\n");
}

} while (choice != 3);

return 0;
}

OUTPUT:
(B) TWO LEVEL DIRECTORY ORGANIZATION

CODE:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_FILES 100
#define MAX_FILENAME 20
#define MAX_SUBDIRECTORIES 10
#define MAX_SUBDIR_NAME 20
struct File {
char filename[MAX_FILENAME];
// You can add more attributes to the file structure if needed
};
struct Directory {
char dirname[MAX_SUBDIR_NAME];
struct File files[MAX_FILES];
int numFiles;
};
struct TwoLevelFileSystem {
struct Directory directories[MAX_SUBDIRECTORIES];
int numDirectories;
};
void initializeFileSystem(struct TwoLevelFileSystem *fs) {
fs->numDirectories = 0;
}
void initializeDirectory(struct Directory *dir, const char *dirname)
{ strncpy(dir->dirname, dirname, MAX_SUBDIR_NAME - 1);
dir->dirname[MAX_SUBDIR_NAME - 1] = '\0';
dir->numFiles = 0;
}
void addFile(struct Directory *dir, const char *filename)
{ if (dir->numFiles < MAX_FILES) {
strncpy(dir->files[dir->numFiles].filename, filename, MAX_FILENAME - 1);
dir->files[dir->numFiles].filename[MAX_FILENAME - 1] = '\0';
dir->numFiles++;
printf("File '%s' added to directory '%s'.\n", filename, dir->dirname);
} else {
printf("Directory is full. Cannot add file '%s' to directory '%s'.\n", filename, dir-
>dirname);
}
}
void listFiles(struct Directory *dir) {
printf("Files in directory '%s':\n", dir->dirname);
for (int i = 0; i < dir->numFiles; i++) {
printf("%s\n", dir->files[i].filename);
}
}
int main() {
struct TwoLevelFileSystem myFileSystem;
initializeFileSystem(&myFileSystem);
int choice;
char dirname[MAX_SUBDIR_NAME];
char filename[MAX_FILENAME];
do {
printf("\n1. Create Directory\n");
printf("2. Add File to Directory\n");
printf("3. List Files in Directory\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the directory name: ");
scanf("%s", dirname);
initializeDirectory(&myFileSystem.directories[myFileSystem.numDirectories],
dirname);
myFileSystem.numDirectories++;
printf("Directory '%s' created successfully.\n", dirname);
break;
case 2:
printf("Enter the directory name: ");
scanf("%s", dirname);
int found = 0;
for (int i = 0; i < myFileSystem.numDirectories; i++) {
if (strcmp(myFileSystem.directories[i].dirname, dirname) == 0) {
found = 1;
printf("Enter the filename: ");
scanf("%s", filename);
addFile(&myFileSystem.directories[i], filename);
break;
}
}
if (!found) {
printf("Directory '%s' not found.\n", dirname);
}
break;
case 3:
printf("Enter the directory name: ");
scanf("%s", dirname);
found = 0;
for (int i = 0; i < myFileSystem.numDirectories; i++) {
if (strcmp(myFileSystem.directories[i].dirname, dirname) == 0) {
found = 1;
listFiles(&myFileSystem.directories[i]);
break;
}
}
if (!found) {
printf("Directory '%s' not found.\n", dirname);
}
break;
case 4:
printf("Exiting the program.\n");
break;
default:
printf("Invalid choice. Please enter a valid option.\n");
}

} while (choice != 4);

return 0;
}

OUTPUT:
(C) HIERARCHIAL DIRECTORY ORGANIZATION

CODE:

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

#define MAX_FILES 100


#define MAX_FILENAME 20
#define MAX_SUBDIRECTORIES 10
#define MAX_SUBDIR_NAME 20

struct File {
char filename[MAX_FILENAME];
// You can add more attributes to the file structure if needed
};

struct Directory {
char dirname[MAX_SUBDIR_NAME];
struct File files[MAX_FILES];
int numFiles;
struct Directory *subdirectories[MAX_SUBDIRECTORIES];
int numSubdirectories;
};

struct HierarchicalFileSystem {
struct Directory root;
};

void initializeFileSystem(struct HierarchicalFileSystem *fs)


{ strcpy(fs->root.dirname, "Root");
fs->root.numFiles = 0;
fs->root.numSubdirectories = 0;
}

void initializeDirectory(struct Directory *dir, const char *dirname)


{ strncpy(dir->dirname, dirname, MAX_SUBDIR_NAME - 1);
dir->dirname[MAX_SUBDIR_NAME - 1] = '\0';
dir->numFiles = 0;
dir->numSubdirectories = 0;
}

void addFile(struct Directory *dir, const char *filename)


{ if (dir->numFiles < MAX_FILES) {
strncpy(dir->files[dir->numFiles].filename, filename, MAX_FILENAME - 1);
dir->files[dir->numFiles].filename[MAX_FILENAME - 1] = '\0';
dir->numFiles++;
printf("File '%s' added to directory '%s'.\n", filename, dir->dirname);
} else {
printf("Directory is full. Cannot add file '%s' to directory '%s'.\n", filename, dir-
>dirname);
}
}

void addSubdirectory(struct Directory *parent, struct Directory *subdirectory) {


if (parent->numSubdirectories < MAX_SUBDIRECTORIES) {
parent->subdirectories[parent->numSubdirectories] =
subdirectory; parent->numSubdirectories++;
printf("Subdirectory '%s' added to directory '%s'.\n", subdirectory->dirname, parent-
>dirname);
} else {
printf("Directory is full. Cannot add subdirectory '%s' to directory '%s'.\n", subdirectory-
>dirname, parent->dirname);
}
}

void listFilesAndSubdirectories(struct Directory *dir) {


printf("Contents of directory '%s':\n", dir->dirname);

printf("Files:\n");
for (int i = 0; i < dir->numFiles; i++) {
printf("%s\n", dir->files[i].filename);
}

printf("Subdirectories:\n");
for (int i = 0; i < dir->numSubdirectories; i++) {
printf("%s\n", dir->subdirectories[i]->dirname);
}
}

int main() {
struct HierarchicalFileSystem myFileSystem;
initializeFileSystem(&myFileSystem);

struct Directory subDir1, subDir2;


initializeDirectory(&subDir1, "Subdirectory1");
initializeDirectory(&subDir2, "Subdirectory2");

addFile(&myFileSystem.root, "RootFile1");

addSubdirectory(&myFileSystem.root, &subDir1);
addFile(&subDir1, "File1");
addFile(&subDir1, "File2");

addSubdirectory(&myFileSystem.root, &subDir2);
addFile(&subDir2, "File3");

int choice;
do {
printf("\n1. List Files and Subdirectories\n");
printf("2. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
listFilesAndSubdirectories(&myFileSystem.root);
break;
case 2:
printf("Exiting the program.\n");
break;
default:
printf("Invalid choice. Please enter a valid option.\n");
}

} while (choice != 2);

return 0;
}

OUTPUT:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy