os-lab-manual(dev c)
os-lab-manual(dev c)
FOR
Operating System Concepts
1
Lab Syllabus for Operating System Concepts
CMP-320
Course Outline
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
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.
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.)
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(&pi, sizeof(pi));
&si,
5
&pi))
return -1;
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.
#include <windows.h>
int main() {
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
if (!CreateProcess(
7
NULL, // Do not inherit thread handle
0, // No creation flags
)) {
return -1;
WaitForSingleObject(pi.hProcess, INFINITE);
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
10
Lab Session # 4
Threads
In this lab session, you will learn about java threads.
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 findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[]) {
14
void findAvgTime(int processes[], int n, int bt[]) {
total_wt += wt[i];
total_tat += tat[i];
int main() {
15
int n;
scanf("%d", &n);
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 findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[]) {
17
findTurnAroundTime(processes, n, bt, wt, tat);
total_wt += wt[i];
total_tat += tat[i];
int main() {
int n;
scanf("%d", &n);
18
int processes[n], burst_time[n];
scanf("%d", &burst_time[i]);
findAvgTime(processes, n, burst_time);
return 0;
PRIORITY
#include <stdio.h>
void findWaitingTime(int processes[], int n, int bt[], int wt[], int priority[]) {
19
// Calculate waiting time for each process
void findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[]) {
// Function to find the average waiting time and average turnaround time
20
total_wt += wt[i];
total_tat += tat[i];
int temp, i, j;
temp = bt[i];
bt[i] = bt[j];
21
bt[j] = temp;
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;
scanf("%d", &n);
22
// Input burst times and priorities for each process
scanf("%d", &burst_time[i]);
printf("Priority: ");
scanf("%d", &priority[i]);
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).
void findWaitingTime(int processes[], int n, int bt[], int wt[], int quantum) {
int remaining_bt[n];
remaining_bt[i] = bt[i];
while (1) {
int done = 1;
if (remaining_bt[i] > 0) {
done = 0;
24
if (remaining_bt[i] > quantum) {
t += quantum;
remaining_bt[i] -= quantum;
} else {
t += remaining_bt[i];
remaining_bt[i] = 0;
if (done == 1) {
break;
void findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[]) {
25
}
total_wt += wt[i];
total_tat += tat[i];
26
printf("Average turnaround time: %.2f\n", (float)total_tat / n);
int main() {
int n, quantum;
scanf("%d", &n);
scanf("%d", &burst_time[i]);
scanf("%d", &quantum);
27
// Calculate and display average waiting time and turnaround time
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>
bool isSafe(int processes[], int avail[], int max[][R], int alloc[][R], int need[][R], int n) {
int work[R];
bool finish[n];
finish[i] = false;
int count = 0;
29
bool progressMade = false;
if (!finish[i]) {
canComplete = false;
break;
if (canComplete) {
count++;
progressMade = true;
if (!progressMade) {
30
return true; // All processes can finish
int main() {
{7, 5, 3},
{3, 2, 2},
{9, 0, 2},
{2, 2, 2},
{4, 3, 3}
};
{0, 1, 0},
{2, 0, 0},
{3, 0, 2},
{2, 1, 1},
{0, 0, 2}
};
int need[P][R];
31
}
} else {
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>
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
}
// 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];
}
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];
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
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).
#include<iomanip>
struct PriorityString
int PageNo;
PriorityString* link;
};
struct Frame
int PageNo;
};
class LeastRecentlyUsed
private:
bool found;
int PageFault;
int TotalFrame;
///////Pointers////////
public:
LeastRecentlyUsed(void);
void Welcome(void);
void TakeFrame(void);
void ShowFault(void);
void FindFault(void);
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;
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;
void LeastRecentlyUsed::FindFault(void)
Frame* FindFrame;
while(head != NULL)
temp = head;
head = head->link;
FindFrame = RecentlyUsed;
if(FindFrame->PageNo == temp->PageNo)
found = true;
break;
39
else
FindFrame = FindFrame->right;
found = true;
moveDownAndReplace(FindFrame,temp);
//RecentlyUsed->PageNo = temp->PageNo;
delete temp;
if(found == false)
PageFault++;
else
found = false;
void LeastRecentlyUsed::TakeFrame(void)
cout << "How many free frame you want to take for process:_ ";
RecentlyUsed = temp;
RecentlyUsed->PageNo = -999;
40
leastRecentlyUsed = temp;
temp->left = NULL;
temp->right = NULL;
temp->right = NULL;
leastRecentlyUsed->right = temp;
temp->left = leastRecentlyUsed;
leastRecentlyUsed = temp;
leastRecentlyUsed->PageNo = -999;
void LeastRecentlyUsed::ShowFault(void)
void LeastRecentlyUsed::EnterPriorityString(void)
int length;
PriorityString* temp;
int i = 0;
41
temp = new PriorityString;
temp->link = NULL;
if(head == NULL)
head = temp;
last = head;
else
last->link = temp;
last = temp;
i++;
void LeastRecentlyUsed::ShowPriorityString(void)
PriorityString*temp = head;
while(temp!=NULL)
temp = temp->link;
42
cout << endl;
LeastRecentlyUsed::~LeastRecentlyUsed(void)
while(head != NULL)
head = head->link;
delete temp;
temp = head;
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).
#include <stdlib.h>
#include <stdbool.h>
#define MAX_PAGES 5 // Size of the page buffer (how many pages can be stored in memory)
typedef struct {
} Page;
45
void printBuffer(Page buffer[], int buffer_size) {
if (buffer[i].is_present)
printf("\n");
int lru_index = 0;
// Find the least recently used page (the first one to evict)
lru_index = i;
buffer[lru_index].page_id = page_id;
buffer[lru_index].is_present = true;
46
// Function to simulate page buffering
page_found = true;
break;
if (!page_found) {
buffer[*buffer_size].page_id = page_id;
buffer[*buffer_size].is_present = true;
(*buffer_size)++;
} else {
47
printBuffer(buffer, *buffer_size);
int main() {
Page buffer[MAX_PAGES] = {{-1, false}, {-1, false}, {-1, false}, {-1, false}, {-1, false}}; //
Initialize empty buffer
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