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

os-lab-manual(dev c)

The document is a lab manual for the Operating Systems course (CMP-320), detailing the course outline, objectives, learning outcomes, assessment criteria, and policies. It includes a syllabus with practical lab sessions covering topics such as process creation, inter-process communication, threading, CPU scheduling algorithms, and memory management. Students are expected to implement various algorithms using C++ and Java, with specific assignments and exercises provided for hands-on learning.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

os-lab-manual(dev c)

The document is a lab manual for the Operating Systems course (CMP-320), detailing the course outline, objectives, learning outcomes, assessment criteria, and policies. It includes a syllabus with practical lab sessions covering topics such as process creation, inter-process communication, threading, CPU scheduling algorithms, and memory management. Students are expected to implement various algorithms using C++ and Java, with specific assignments and exercises provided for hands-on learning.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

LAB MANUAL

FOR
Operating System Concepts

1
Lab Syllabus for Operating System Concepts
CMP-320
Course Outline

Title Operating Systems Lab Manual

Credit Hours 1

Prerequisite -

15 Lectures
Required
Study Hours
class BSSE

Aims and Through this lab work the students will learn the practical implementation of algorithms
Objectives to understand the basic concepts of operating systems. The course will use C++ and
Java for labs and programming projects and teaches the implementation of main
concepts of operating systems like CPU scheduling algorithms, Page replacement
algorithms, process creation, threads etc.

Learning Upon successful completion of this course, the students will be able to:
Outcomes
1. Understand the implementation of basic concepts and algorithms of operating
systems
Text Book/s Operating System concepts by Silberchatz, Galvin, Gagne, (Tenth Edition)

Reference
Books

Instructional Class Assessment Mid Final Total


Aids/Resourc 20% 30% 50%
es 100%

Lab Work

Assessment
Criteria

2
Policies and Class Attendance and Absenteeism
Regulations
Students are required to attend all classes and lab meetings. Regular attendance in
their class/laboratory sessions will be very helpful to maintain a satisfactory progress
throughout their course. Attendance will be strictly enforced and evaluated according
to the Student Attendance Control Criteria announced by the DOCSIT and UOS. Any
student who exceeds the maximum allowable absence limit during the course will not
be allowed to sit in the exams. The maximum allowed limit for this course is 25% which
include both excused and unexcused absences.

Academic Integrity

Cheating in any form will not be tolerated and could lead to severe consequences.
Academic work submitted by the students in the form of homework, assignment, or a
project must be the result of their own effort.

Make-Up Exam Policy

A student who has missed an exam will be allowed to sit in a make-up exam only if he
or she provides a medical report from a government hospital/clinic.

General Behavior

Students must maintain a good behavior both in and outside their classes. They are
required to keep their mobile phones switched off while attending their class/laboratory
sessions or writing their exams. Any student who engages in a behavior that disrupts
the learning environment may face disciplinary action under the UOS code. Students
must also maintain a smoke free environment in all college facilities.

Recommenda
tions

3
Framework
Week Study Hours

Topic Source
(Book-
Chapter No.
Article no.)

Process Creation Chapter 3 2


 Parent child processes
1,2 concept
 Creation of child process
Inter Process Communication

 Sockets
3
 1 Handout
Chapter 3 2

Threads
Chapter 4
4,5
 Java Threads 2

Implementation of Scheduling 2
Chapter 5
Algorithms
6
 FIFO, SJF, Priority
Scheduling
Implementation of Scheduling 2
Algorithms
7,8
Chapter 5
 SRF, Round Robin
Deadlocks
9
 Implementation of Banker’s Chapter 7 2
Algorithm
Memory Management
Algorithms
10 Chapter 8 2
 Implementation of first fit
 Implementation of Best fit
Implementation of Page 2
Replacement Algorithm
Chapter 9
11
 Implementation of FIFO,
LRU

Implementation of Page
Replacement Algorithm Chapter 9
12 2
Implementation of Page

Buffering, LFU
Implementation of Page 2
Replacement Algorithm Chapter 9
13
 Implementation of Page
Buffering, MFU

4
Lab Session # 1,2
In this lab session, you will learn about process creation, process control and process termination in windows.
More specifically, we will focus on using the CreateProcess Win32 API. The following code implements
process creation in Windows. Visual C++ 6.0 IDE is recommended for editing/compiling the program.

#include<stdio.h>

#include<windows.h>

int main()

STARTUPINFO si;

PROCESS_INFORMATION pi;

// allocate memory

ZeroMemory(&si, sizeof (si)) ;

si.cb = sizeof (si) ;

ZeroMemory(&pi, sizeof(pi));

// create child process

if (!CreateProcess(NULL, // use command line

"C:\\WINDOWS\\system32\\mspaint.exe", // command lin

NULL, // don’t inherit process handle

NULL, // don’t inherit thread handle

FALSE, // disable handle inheritance

0, //no creation flags

NULL, // use parent’s environment block

NULL, // use parent’s existing directory

&si,

5
&pi))

fprintf(stderr, "Create Process Failed");

return -1;

// parent will wait for the child to complete

WaitForSingleObject(pi.hProcess, INFINITE);

printf("Child Complete");

// close handles

CloseHandle(pi.hProcess);

CloseHandle(pi.hThread);

The Procedure CreateProcess has the following form (you don’t have to implement CreateProcess).
BOOL CreateProcess(
LPCTSTR lpApplicationName, // name of executable module
LPTSTR lpCommandLine, // command line string
LPSECURITY_ATTRIBUTES lpProcessAttributes, // SD
LPSECURITY_ATTRIBUTES lpThreadAttributes, // SD
BOOL fInheritHandles, // handle inheritance option
DWORD dwCreationFlags, // creation flags
LPVOID lpEnvironment, // new envirnment block
LPCTSTR lpCurrentDirectory, // current directory name
LPSTARTUPINFO lpStartupInfo, // startup information
LPPROCESS_INFORMATION lpProcessInformation // process information
);

Part – I
Implement the code segment given at the start of the first page in Visual C++. Create a win32 console
application (empty project) names “ProcessCreate”. Then go to the file view and add a file process.c,
implement the code in this file.

Part – II
Experiment by executing different types of applications using the child process e.g. notepad.

Part – III

6
Create a new win32 console application “Hello”. The application should simply display Hello World on the
screen. Compile and build an executable file “Hello.exe” for this program. Place the executable in the same
folder as the “ProcessCreate” source files. Then modify the “ProcessCreate” source code to execute the Hello
world executable.

Implemetaion of Grand Parent

#include <windows.h>

int main() {

STARTUPINFO si;

PROCESS_INFORMATION pi;

// Initialize memory for structures

ZeroMemory(&si, sizeof(si));

si.cb = sizeof(si);

ZeroMemory(&pi, sizeof(pi));

printf("Grand Parent process runs.\n");

getchar(); // Wait for user input

// Create a child process

if (!CreateProcess(

NULL, // Use command line

"C:\\Windows\\System32\\notepad.exe", // Path to Notepad

NULL, // Do not inherit process handle

7
NULL, // Do not inherit thread handle

FALSE, // Disable handle inheritance

0, // No creation flags

NULL, // Use parent's environment block

NULL, // Use parent's existing directory

&si, // Pointer to STARTUPINFO structure

&pi // Pointer to PROCESS_INFORMATION structure

)) {

fprintf(stderr, "CreateProcess failed with error %d.\n", GetLastError());

return -1;

// Parent will wait for child to complete

WaitForSingleObject(pi.hProcess, INFINITE);

printf("Child process completed.\n");

// Close process and thread handles

CloseHandle(pi.hProcess);

CloseHandle(pi.hThread);

return 0;

8
Lab Session # 3
Sockets
In this lab session, you will learn about sockets in java for inter-process communication.

import java.net.*;
import java.io.*;
public class DateServer
{
public static void main(String[] args) {
try {
ServerSocket sock = new ServerSocket(6013);
/* now listen for connections */
while (true)
{
Socket client = sock.accept();
PrintWriter pout = new PrintWriter(client.getOutputStream(),
true);
/* write the Date to the socket */
pout.println(new java.util.Date().toString());
/* close the socket and resume */
/* listening for connections */
client.close();
}
}
catch (IOException ioe) {
System.err.println(ioe);
}
}
}

import java.net.*;
import java.io.*;
public class DateClient
{
public static void main(String[] args) {
try {
/* make connection to server socket */
Socket sock = new Socket("127.0.0.1",6013);
InputStream in = sock.getInputStream();
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
/* read the date from the socket */
String line;
while ( (line = bin.readLine()) != null)
System.out.println(line);
/* close the socket connection*/
9
sock.close();
}
catch (IOException ioe) {
System.err.println(ioe);
}
}

Assignment

Implement an echo server

10
Lab Session # 4
Threads
In this lab session, you will learn about java threads.

// Create a second thread by extending Thread


class NewThread extends Thread {
NewThread()
{
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
}
catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ExtendThread
{
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
Assignment
Write down a program that creates 3 child threads.
11
Lab Session # 5
Threads
In this lab session, you will learn to write a java program for summation of non negative integers.

Here is the code for creating named pipe


class Sum
{
private int sum;
public int getSum() {
return sum;
}
public void setSum(int sum) {
this.sum = sum;
}
}
class Summation implements Runnable
{
private int upper;
private Sum sumValue;
public Summation(int upper, Sum sumValue) {
this.upper = upper;
this.sumValue = sumValue;
}
public void run() {
int sum = 0;
for (int i = 0; i <= upper; i++)
sum += i;
sumValue.setSum(sum);
}
}
public class Driver
{
public static void main(String[] args) {
if (args.length > 0) {
if (Integer.parseInt(args[0]) < 0)
System.err.println(args[0] + " must be >= 0.");
else {
Sum sumObject = new Sum();
int upper = Integer.parseInt(args[0]);
Thread thrd = new Thread(new Summation(upper, sumObject));
thrd.start();
try {
thrd.join();
System.out.println
("The sum of "+upper+" is "+sumObject.getSum());
12
}
catch (InterruptedException ie) { }
}
}
else
System.err.println("Usage: Summation <integer value>"); }
}

Practice Question

Q1. Implement the code given above and show the output.
Q2. Modify the program so that we have only two threads created. The first should call
print_hello1 and the second should call print_hello2. Both functions should have for loops for
100 times and should display line “Executing thread no. 1” or “Executing thread no. 2”. Is
the output interleaved or not. Why?
Q3. Use two threads to show two rotating bars at the two top corners of a screen. Basically
each thread will be driving the “rotation” of the bar. (Hint: You can use “\” and “/” to achieve
the effect but you will have to figure out how to achieve the effect of “rotation”.)
Q4. For the program developed in Q3, modify it so that on the pressing “1” the left bar starts
rotating i.e. thread 1 starts executing and on pressing “2”, the left bar stops and the right bar
starts executing. If “1” is pressed again then the left bar starts rotating again but the right bar
stops rotating. (Hint: Think in terms of suspend and resume)

13
Lab Session # 6, 7
Implementation of CPU Scheduling Algorithms

In this lab session, you will learn implementation of FIFO (non preemptive) CPU scheduling algorithm. The
following code reads number of processes their cpu burst and displays average turnaround time and average
waiting time. Visual C++ 6.0 IDE is recommended for editing/compiling the program(s).

Implementation of FCFS

#include <stdio.h>

void findWaitingTime(int processes[], int n, int bt[], int wt[]) {

wt[0] = 0; // First process has no waiting time

// Calculate waiting time for each process

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

wt[i] = bt[i - 1] + wt[i - 1];

void findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[]) {

// Turnaround time = Burst time + Waiting time

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

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

14
void findAvgTime(int processes[], int n, int bt[]) {

int wt[n], tat[n];

int total_wt = 0, total_tat = 0;

findWaitingTime(processes, n, bt, wt);

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

// Calculate total waiting time and turnaround time

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

total_wt += wt[i];

total_tat += tat[i];

// Display the results

printf("Process\tBurst Time\tWaiting Time\tTurnaround Time\n");

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

printf("%d\t%d\t\t%d\t\t%d\n", processes[i], bt[i], wt[i], tat[i]);

printf("\nAverage waiting time: %.2f\n", (float)total_wt / n);

printf("Average turnaround time: %.2f\n", (float)total_tat / n);

int main() {

15
int n;

// Input the number of processes

printf("Enter the number of processes: ");

scanf("%d", &n);

int processes[n], burst_time[n];

// Input burst times for each process

printf("Enter burst times for each process:\n");

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

processes[i] = i + 1; // Process numbers

printf("Burst time of process %d: ", processes[i]);

scanf("%d", &burst_time[i]);

findAvgTime(processes, n, burst_time);

return 0;

Exercise

Implement SJF and Priority scheduling algorithm. Read no of processes their arrival time cpu burst
and priority from user. The program should compute the average turnaround time and average
waiting time

16
#include <stdio.h>

void findWaitingTime(int processes[], int n, int bt[], int wt[]) {

wt[0] = 0; // First process has no waiting time

// Calculate waiting time for each process

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

wt[i] = bt[i - 1] + wt[i - 1];

void findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[]) {

// Turnaround time = Burst time + Waiting time

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

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

void findAvgTime(int processes[], int n, int bt[]) {

int wt[n], tat[n];

int total_wt = 0, total_tat = 0;

findWaitingTime(processes, n, bt, wt);

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

// Calculate total waiting time and turnaround time

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

total_wt += wt[i];

total_tat += tat[i];

// Display the results

printf("Process\tBurst Time\tWaiting Time\tTurnaround Time\n");

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

printf("%d\t%d\t\t%d\t\t%d\n", processes[i], bt[i], wt[i], tat[i]);

printf("\nAverage waiting time: %.2f\n", (float)total_wt / n);

printf("Average turnaround time: %.2f\n", (float)total_tat / n);

int main() {

int n;

// Input the number of processes

printf("Enter the number of processes: ");

scanf("%d", &n);

18
int processes[n], burst_time[n];

// Input burst times for each process

printf("Enter burst times for each process:\n");

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

processes[i] = i + 1; // Process numbers

printf("Burst time of process %d: ", processes[i]);

scanf("%d", &burst_time[i]);

findAvgTime(processes, n, burst_time);

return 0;

PRIORITY
#include <stdio.h>

// Function to find waiting time for each process

void findWaitingTime(int processes[], int n, int bt[], int wt[], int priority[]) {

wt[0] = 0; // First process has no waiting time

19
// Calculate waiting time for each process

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

wt[i] = bt[i - 1] + wt[i - 1];

// Function to find turnaround time for each process

void findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[]) {

// Turnaround time = Burst time + Waiting time

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

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

// Function to find the average waiting time and average turnaround time

void findAvgTime(int processes[], int n, int bt[], int priority[]) {

int wt[n], tat[n];

int total_wt = 0, total_tat = 0;

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

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

// Calculate total waiting time and turnaround time

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

20
total_wt += wt[i];

total_tat += tat[i];

// Display the results

printf("Process\tBurst Time\tPriority\tWaiting Time\tTurnaround Time\n");

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

printf("%d\t%d\t\t%d\t\t%d\t\t%d\n", processes[i], bt[i], priority[i], wt[i], tat[i]);

printf("\nAverage waiting time: %.2f\n", (float)total_wt / n);

printf("Average turnaround time: %.2f\n", (float)total_tat / n);

// Function to sort the processes based on priority (for priority scheduling)

void sortProcesses(int processes[], int bt[], int priority[], int n) {

int temp, i, j;

for (i = 0; i < n - 1; i++) {

for (j = i + 1; j < n; j++) {

if (priority[i] > priority[j]) {

// Swap burst time

temp = bt[i];

bt[i] = bt[j];

21
bt[j] = temp;

// Swap process IDs

temp = processes[i];

processes[i] = processes[j];

processes[j] = temp;

// Swap priorities

temp = priority[i];

priority[i] = priority[j];

priority[j] = temp;

int main() {

int n;

// Input the number of processes

printf("Enter the number of processes: ");

scanf("%d", &n);

int processes[n], burst_time[n], priority[n];

22
// Input burst times and priorities for each process

printf("Enter burst times and priorities for each process:\n");

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

processes[i] = i + 1; // Process numbers

printf("For process %d:\n", processes[i]);

printf("Burst time: ");

scanf("%d", &burst_time[i]);

printf("Priority: ");

scanf("%d", &priority[i]);

// Sort processes based on priority

sortProcesses(processes, burst_time, priority, n);

// Calculate and display average waiting time and turnaround time

findAvgTime(processes, n, burst_time, priority);

return 0;

23
Lab Session # 8
Implementation of CPU Scheduling Algorithms

In this lab session, you will learn implementation of Round Robin (preemptive) CPU scheduling algorithm. The
following code reads number of processes their cpu burst and displays average turnaround time and average
waiting time. Visual C++ 6.0 IDE is recommended for editing/compiling the program(s).

Implementation of Round Robin


#include <stdio.h>

void findWaitingTime(int processes[], int n, int bt[], int wt[], int quantum) {

int remaining_bt[n];

// Copy burst times to remaining burst times array

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

remaining_bt[i] = bt[i];

int t = 0; // Track total time

while (1) {

int done = 1;

// Traverse all processes

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

if (remaining_bt[i] > 0) {

done = 0;
24
if (remaining_bt[i] > quantum) {

t += quantum;

remaining_bt[i] -= quantum;

} else {

t += remaining_bt[i];

wt[i] = t - bt[i]; // Waiting time

remaining_bt[i] = 0;

// If all processes are finished, break

if (done == 1) {

break;

void findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[]) {

// Turnaround time = Burst time + Waiting time

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

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

25
}

void findAvgTime(int processes[], int n, int bt[], int quantum) {

int wt[n], tat[n];

int total_wt = 0, total_tat = 0;

// Calculate waiting time

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

// Calculate turnaround time

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

// Calculate total waiting time and turnaround time

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

total_wt += wt[i];

total_tat += tat[i];

// Display the results

printf("Process\tBurst Time\tWaiting Time\tTurnaround Time\n");

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

printf("%d\t%d\t\t%d\t\t%d\n", processes[i], bt[i], wt[i], tat[i]);

printf("\nAverage waiting time: %.2f\n", (float)total_wt / n);

26
printf("Average turnaround time: %.2f\n", (float)total_tat / n);

int main() {

int n, quantum;

// Input the number of processes

printf("Enter the number of processes: ");

scanf("%d", &n);

int processes[n], burst_time[n];

// Input burst times for each process

printf("Enter burst times for each process:\n");

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

processes[i] = i + 1; // Process numbers

printf("Burst time of process %d: ", processes[i]);

scanf("%d", &burst_time[i]);

// Input time quantum

printf("Enter the time quantum: ");

scanf("%d", &quantum);

27
// Calculate and display average waiting time and turnaround time

findAvgTime(processes, n, burst_time, quantum);

return 0;

Implement SRF (preemptive) scheduling algorithm. Read no of processes their arrival time cpu burst
and priority from user. The program should compute the average turnaround time and average
waiting time

28
Lab Session # 9
Banker’s Algorithm

In this lab session, you will learn the banker’s algorithm to check the safe state and resource allocation
algorithm’s implementation. Following code reads the number of processes, required resources, systems
maximum resources. Then it gets requirements of process and after checking safe state allocate resources.
Visual C++ 6.0 IDE is recommended for editing/compiling the program(s).

#include <stdio.h>

#include <stdbool.h>

#define P 5 // Number of processes

#define R 3 // Number of resources

// Function to check if a process can be completed with current available resources

bool isSafe(int processes[], int avail[], int max[][R], int alloc[][R], int need[][R], int n) {

int work[R];

bool finish[n];

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

work[i] = avail[i]; // Initialize work to available resources

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

finish[i] = false;

int count = 0;

while (count < n) {

29
bool progressMade = false;

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

if (!finish[i]) {

bool canComplete = true;

// Check if process i can be completed

for (int j = 0; j < R; j++) {

if (need[i][j] > work[j]) {

canComplete = false;

break;

// If process can be completed, simulate resource allocation

if (canComplete) {

for (int j = 0; j < R; j++) {

work[j] += alloc[i][j]; // Release the resources

finish[i] = true; // Mark process as finished

count++;

progressMade = true;

if (!progressMade) {

return false; // No progress means the system is in an unsafe state

30
return true; // All processes can finish

int main() {

int processes[P] = {0, 1, 2, 3, 4}; // Process IDs

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

int max[P][R] = { // Maximum resource needs for each process

{7, 5, 3},

{3, 2, 2},

{9, 0, 2},

{2, 2, 2},

{4, 3, 3}

};

int alloc[P][R] = { // Currently allocated resources for each process

{0, 1, 0},

{2, 0, 0},

{3, 0, 2},

{2, 1, 1},

{0, 0, 2}

};

// Need matrix (Max - Alloc)

int need[P][R];

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

for (int j = 0; j < R; j++) {

need[i][j] = max[i][j] - alloc[i][j];

31
}

// Check if the system is in a safe state

if (isSafe(processes, avail, max, alloc, need, P)) {

printf("The system is in a safe state.\n");

} else {

printf("The system is not in a safe state.\n");

return 0;

Exercise

Implement the deadlock detection algorithm for n no of processes after reading maximum, allocated resources
and remaining needs.

32
Lab Session # 11
Implementation of Best Fit and First Fit Memory Management
Algorithms

In this lab session, you will learn the implementation of best fit and first fit memory management algorithms.
Visual C++ 6.0 IDE is recommended for editing/compiling the program(s).

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

#define MAX 5 // Maximum number of processes


#define RESOURCES 3 // Number of resource types

// Function to calculate if the system is in a safe state


bool isSafe(int processes[], int avail[], int max[][RESOURCES], int alloc[][RESOURCES], int need[]
[RESOURCES], int n) {
int work[RESOURCES], finish[n];
for (int i = 0; i < RESOURCES; i++) {
work[i] = avail[i]; // Copy available resources to work
}
for (int i = 0; i < n; i++) {
finish[i] = 0; // Mark all processes as not finished
}

int count = 0;
while (count < n) {
bool found = false;
for (int p = 0; p < n; p++) {
if (!finish[p]) {
int canAllocate = 1;
// Check if the process needs fewer or equal resources than available
for (int r = 0; r < RESOURCES; r++) {
if (need[p][r] > work[r]) {
canAllocate = 0;
break;
}
}
// If yes, allocate the resources to the process and mark it finished
if (canAllocate) {
for (int r = 0; r < RESOURCES; r++) {
33
work[r] += alloc[p][r]; // Release allocated resources
}
finish[p] = 1; // Process is finished
count++;
found = true;
}
}
}
// If no process was found, the system is in an unsafe state
if (!found) {
return false;
}
}
return true; // All processes can finish
}

// Function to request resources from a process


bool requestResources(int processes[], int avail[], int max[][RESOURCES], int alloc[]
[RESOURCES], int need[][RESOURCES], int processID, int request[]) {
// Check if request is valid (less than or equal to need and available)
for (int i = 0; i < RESOURCES; i++) {
if (request[i] > need[processID][i]) {
printf("Error: Process has exceeded maximum claim.\n");
return false;
}
if (request[i] > avail[i]) {
printf("Error: Not enough resources available.\n");
return false;
}
}

// Pretend to allocate the resources and check if the system remains in a safe state
for (int i = 0; i < RESOURCES; i++) {
avail[i] -= request[i]; // Allocate resources
alloc[processID][i] += request[i];
need[processID][i] -= request[i];
}

// Check if the system is still in a safe state


if (isSafe(processes, avail, max, alloc, need, MAX)) {
return true; // Request is safe
} else {
// If not safe, revert the changes

34
for (int i = 0; i < RESOURCES; i++) {
avail[i] += request[i]; // Revert resources
alloc[processID][i] -= request[i];
need[processID][i] += request[i];
}
printf("Error: System would enter an unsafe state if request is granted.\n");
return false; // Request leads to an unsafe state
}
}

int main() {
int processes[MAX] = {0, 1, 2, 3, 4};
int avail[RESOURCES] = {3, 3, 2}; // Available resources
int max[MAX][RESOURCES] = {
{7, 5, 3},
{3, 2, 2},
{9, 0, 2},
{2, 2, 2},
{4, 3, 3}
};
int alloc[MAX][RESOURCES] = {
{0, 1, 0},
{2, 0, 0},
{3, 0, 2},
{2, 1, 1},
{0, 0, 2}
};
int need[MAX][RESOURCES];

// Calculate the need matrix (Need[i][j] = Max[i][j] - Alloc[i][j])


for (int i = 0; i < MAX; i++) {
for (int j = 0; j < RESOURCES; j++) {
need[i][j] = max[i][j] - alloc[i][j];
}
}

printf("Current system state:\n");


printf("Available resources: ");
for (int i = 0; i < RESOURCES; i++) {
printf("%d ", avail[i]);
}
printf("\n\n");

35
// Request resources for process 1 (example)
int request[] = {1, 0, 2}; // Request for 1 unit of resource 1, 0 of resource 2, and 2 of resource
3
int processID = 1; // Process 1

if (requestResources(processes, avail, max, alloc, need, processID, request)) {


printf("Resources allocated successfully!\n");
} else {
printf("Resources allocation failed.\n");
}

return 0;
}

Exercise
Implement best fit and first fit Memory management algorithme.

36
Lab Session # 12
Page Replacement Algorithm

In this lab session, you will learn the implementation of page replacement algorithms. Following code reads
the number of free frames and a reference string. At the end it will display the number of page faults. Visual C+
+ 6.0 IDE is recommended for editing/compiling the program(s).

Implementation of LRU Page Replacement Algorithm


#include<iostream>

#include<iomanip>

using namespace std;

struct PriorityString

int PageNo;

PriorityString* link;

};

struct Frame

int PageNo;

Frame* left, *right;

};

class LeastRecentlyUsed

private:

bool found;

int PageFault;

int TotalFrame;

///////Pointers////////

PriorityString* head, *last;


37
Frame* RecentlyUsed, *leastRecentlyUsed;

public:

LeastRecentlyUsed(void);

void Welcome(void);

void TakeFrame(void);

void ShowFault(void);

void FindFault(void);

void moveDownAndReplace(Frame* FindFrame, PriorityString* data);

void EnterPriorityString(void);

void ShowPriorityString(void);

virtual ~LeastRecentlyUsed(void);

};

LeastRecentlyUsed::LeastRecentlyUsed(void)

found = false;

PageFault = 0;

TotalFrame = 0;

head = NULL;

last = NULL;

RecentlyUsed = NULL;

leastRecentlyUsed = NULL;

void LeastRecentlyUsed::moveDownAndReplace(Frame * FindFrame, PriorityString* data)

Frame* temp = FindFrame;

Frame* temp1 = FindFrame->left;

cout << setw(25) << "Recently used" << setw(25) << "Previuosly used" << setw(25)
<< "Least recently Used" << endl;

38
cout << setw(25) << RecentlyUsed->PageNo << setw(25) << RecentlyUsed->right-
>PageNo << setw(25) << leastRecentlyUsed->PageNo << endl;

while(temp1 != NULL)

temp->PageNo = temp1->PageNo;

temp = temp1;

temp1 = temp1->left;

RecentlyUsed->PageNo = data->PageNo;

cout << setw(25) << RecentlyUsed->PageNo << setw(25) << RecentlyUsed->right-


>PageNo << setw(25) << leastRecentlyUsed->PageNo << endl;

void LeastRecentlyUsed::FindFault(void)

PriorityString* temp = head;

Frame* FindFrame;

while(head != NULL)

temp = head;

head = head->link;

FindFrame = RecentlyUsed;

while(FindFrame->PageNo != -999 && FindFrame->right != NULL)

if(FindFrame->PageNo == temp->PageNo)

found = true;

break;

39
else

FindFrame = FindFrame->right;

}//end inner while

if(FindFrame == leastRecentlyUsed && FindFrame->PageNo == temp->PageNo)

found = true;

moveDownAndReplace(FindFrame,temp);

//RecentlyUsed->PageNo = temp->PageNo;

delete temp;

if(found == false)

PageFault++;

else

found = false;

}// end outer while

void LeastRecentlyUsed::TakeFrame(void)

cout << "How many free frame you want to take for process:_ ";

cin >> TotalFrame;

cout << endl;

Frame * temp = new Frame;

RecentlyUsed = temp;

RecentlyUsed->PageNo = -999;

40
leastRecentlyUsed = temp;

temp->left = NULL;

temp->right = NULL;

for(int i = 1; i < TotalFrame; i++)

temp = new Frame;

temp->right = NULL;

leastRecentlyUsed->right = temp;

temp->left = leastRecentlyUsed;

leastRecentlyUsed = temp;

leastRecentlyUsed->PageNo = -999;

void LeastRecentlyUsed::ShowFault(void)

cout << "Total page faults are:_ "

<< PageFault << endl;

void LeastRecentlyUsed::EnterPriorityString(void)

int length;

cout << "Please specify length of PriorityString..." ;

cin >> length;

cout << endl;

PriorityString* temp;

int i = 0;

while(i < length )

41
temp = new PriorityString;

cout << "Please enter required page number:_ ";

cin >> temp->PageNo;

temp->link = NULL;

cout << endl;

if(head == NULL)

head = temp;

last = head;

else

last->link = temp;

last = temp;

i++;

}// end while

void LeastRecentlyUsed::ShowPriorityString(void)

PriorityString*temp = head;

while(temp!=NULL)

cout << temp->PageNo << " ";

temp = temp->link;

42
cout << endl;

LeastRecentlyUsed::~LeastRecentlyUsed(void)

PriorityString* temp = head;

while(head != NULL)

head = head->link;

delete temp;

temp = head;

Frame* tempframe = RecentlyUsed;

while(tempframe != NULL)

RecentlyUsed = RecentlyUsed->right;

if(RecentlyUsed != NULL)

RecentlyUsed->left = tempframe->left;

delete tempframe;

tempframe = RecentlyUsed;

int main()

LeastRecentlyUsed pro;

pro.EnterPriorityString();

pro.ShowPriorityString();

43
pro.TakeFrame();

pro.FindFault();

pro.ShowFault();

return 0;

Exercice

Implement FIFO page replacement algorithm. Code should read the number of free frames and a reference
string. At the end it should display the number of page faults.

44
Lab Session # 13, 14
Page Replacement Algorithm

In this lab session, you will learn the implementation of Page Buffering page replacement algorithms.
Following code reads the number of free frames and a reference string. At the end it will display the number of
page faults. Visual C++ 6.0 IDE is recommended for editing/compiling the program(s).

Implementation of Page Buffering


#include <stdio.h>

#include <stdlib.h>

#include <stdbool.h>

#define MAX_PAGES 5 // Size of the page buffer (how many pages can be stored in memory)

#define TOTAL_PAGES 10 // Total number of pages on the disk (simulated)

// Struct to represent a page

typedef struct {

int page_id; // Page identifier (ID)

bool is_present; // Flag to check if the page is present in the buffer

} Page;

// Function to simulate reading a page from disk

void readPageFromDisk(int page_id) {

printf("Reading page %d from disk.\n", page_id);

// Function to print the current page buffer status

45
void printBuffer(Page buffer[], int buffer_size) {

printf("Page Buffer: ");

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

if (buffer[i].is_present)

printf("Page%d ", buffer[i].page_id);

printf("\n");

// Function to perform LRU (Least Recently Used) page replacement

void lruPageReplacement(Page buffer[], int *buffer_size, int page_id) {

int lru_index = 0;

// Find the least recently used page (the first one to evict)

for (int i = 1; i < *buffer_size; i++) {

if (buffer[i].page_id < buffer[lru_index].page_id) {

lru_index = i;

// Evict the least recently used page

printf("Evicting Page %d from buffer.\n", buffer[lru_index].page_id);

// Insert the new page

buffer[lru_index].page_id = page_id;

buffer[lru_index].is_present = true;

printf("Inserting Page %d into buffer.\n", page_id);

46
// Function to simulate page buffering

void pageBuffering(Page buffer[], int *buffer_size, int page_id) {

bool page_found = false;

// Check if the page is already in the buffer

for (int i = 0; i < *buffer_size; i++) {

if (buffer[i].is_present && buffer[i].page_id == page_id) {

page_found = true;

printf("Page %d found in buffer.\n", page_id);

break;

// If the page is not found, perform page replacement

if (!page_found) {

if (*buffer_size < MAX_PAGES) {

// If space is available in the buffer, simply add the page

buffer[*buffer_size].page_id = page_id;

buffer[*buffer_size].is_present = true;

(*buffer_size)++;

printf("Inserting Page %d into buffer.\n", page_id);

} else {

// If the buffer is full, apply LRU page replacement

lruPageReplacement(buffer, buffer_size, page_id);

47
printBuffer(buffer, *buffer_size);

int main() {

// Simulating a page buffer with a maximum of 5 pages in memory

Page buffer[MAX_PAGES] = {{-1, false}, {-1, false}, {-1, false}, {-1, false}, {-1, false}}; //
Initialize empty buffer

int buffer_size = 0; // Tracks the current number of pages in the buffer

// Simulating a sequence of page accesses

int page_access_sequence[] = {1, 2, 3, 4, 5, 1, 6, 2, 7, 8};

int total_accesses = sizeof(page_access_sequence) / sizeof(page_access_sequence[0]);

// Simulate page buffering process

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

int page_id = page_access_sequence[i];

printf("\nAccessing Page %d\n", page_id);

pageBuffering(buffer, &buffer_size, page_id);

return 0;

Exercice

Implementation LFU and MFU page replacement algorithm. Code should read the number of free frames and
a reference string. At the end it should display the number of page faults.

48

You might also like