0% found this document useful (0 votes)
30 views105 pages

Operating System - LabManual v2

This document provides instructions for installing the Windows operating system in 13 steps. It explains how to start the installation process, select language and time settings, accept license terms, choose upgrade or custom installation options, select the drive to install Windows on, customize personal settings, and sign in with a Microsoft account.

Uploaded by

CH HUMZA
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)
30 views105 pages

Operating System - LabManual v2

This document provides instructions for installing the Windows operating system in 13 steps. It explains how to start the installation process, select language and time settings, accept license terms, choose upgrade or custom installation options, select the drive to install Windows on, customize personal settings, and sign in with a Microsoft account.

Uploaded by

CH HUMZA
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/ 105

Mirpur University of Science & Technology, MUST Mirpur

AJ&K

Operating Systems
Lab Manual
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Course Title Operating Systems


Course Code BSE-2405L
Credit Hours 4 (3+1)
CLOs 4
Semester Spring-2023
Course Instructor Engr. Maryum Lab. Instructor Engr. Abdul Qadir Khan
Hamdani

List of Experiments
Lab Experiment CLO
#:
1 Installation of Windows and understanding basics of Windows Operating System 4
2 Implementation of Basic Commands of Disk Operating System 4
3 Understanding and implementation of basic System calls. 4
4 Installation of VMware and Linux and understanding basics of Linux 4
5 Implementation of basic Commands of Linux Operating System 4
6 Implementation of First Come First Served (FCFS) CPU scheduling algorithm 4
7 Implementation of Shortest Job First (SJF) CPU scheduling algorithm 4
8 Implementation of Round Robin algorithm 4
9 Understanding and implementation File allocation strategies-sequential file 4
allocation
10 Understanding and Implementation of File allocation strategies-indexed file 4
allocation
11 Implementation of File allocation strategies-linked file allocation 4
12 Implementation of Producer Consumer Problem (Using Semaphore in C++ 4
13 Implementation of File organization techniques-single level directory and two-level 4
directory
14 Implementation of Banker’s algorithm for deadlock avoidance 4
15 Implementation of deadlock detection algorithm 4
16 Implementation of Least Recently Used (LRU) Page Replacement Policy 4
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Lab Engineer Course Instructor

1
Installation of Windows Operating System and understanding basics of
Windows Operating System

Objectives:

 Familiarize students with the installation process of the Windows operating system.
 Introduce students to the basic features and functionalities of the Windows operating
system.
 Provide hands-on experience in customizing and personalizing the Windows operating
system.

Introduction
In this lab, students are advised to learn about the Windows operating system. They will explore the
concept of an operating system, understand the basic steps involved in installing the operating system,
delve into multitasking capabilities, and discuss the concept of system variables in the operating system.

Introduction to Windows Operating System


The Windows operating systems are more formally called Microsoft Windows and is a family of
operating systems for personal computers. Windows dominates the personal computer world, running, by
some estimates, more than 90 percent of all personal computers – the remainder running Linux and Mac.

Figure 1:Usage of Operating System


Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Windows provides a graphical user interface (GUI), virtual memory management, multitasking, and
support for many peripheral devices. In addition to Windows OS for personal computers, Microsoft also
offers operating systems for servers and personal mobile device

Basic Steps of Installation of Window

The basic steps to install windows 10 operating system are as follow:


Step 1: This is the first Screen when we plug the usb and restart the system and press
the escape or f12 key according to system the first boot screen appears in which we
select the usb oion for installing the window from usb as shown.

Figure 2: Boot Manager

Step 2: After selection of USB flash drive or DVD the next screen appear whereyou
choose the OS’ language, time and currency format, and input method as shown in
Figure 3.

Figure 4: Language and time setting


Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Step 3a: It's obvious what you need to click here. Like Windows 8.x, you can also choose to
repair your computer as shown in Figure 4

Figure 5: Install Now

If you choose the repair option, you will end up at a Troubleshoot screen where you can choose
to reset your PC and re- install windows (you can either keep or remove your files), or access
more advanced troubleshooting options (Figure 5). For the latter, there are options for doing a
system restore (if you’ve a restore point on your PC), image recovery, running commands in
command prompt, and letting Windows fix any startup problems. You can also get to the
advanced startup options after installation via the new Settings app in Windows 10.

Figure 5: Window Repair Option

Figure 6: Trouble Shooting

Step 3b: Traditionally, your Windows product key can be found on your online order info, in the
confirmation email for your purchase, or on the DVD packaging. That said, this is more for a
clean install. If your device has been successfully upgraded to Windows 10, and you choose to
wipe your device and do a clean install later, the device will reactivate without the need of a
Windows 8.x product key.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Figure 7: Product Key

Step 4: Accept the license terms. After you read them, of course. (Figure 7)

Step 5: Next, you’ll be presented with this screen, where you can choose to do either an upgrade
or a custom install as shown in Figure 8

Figure 8: Terms and conditions

Figure 9: type of Installation.


Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Step 6: Here’s where you select the drive to install Windows 10 on. You can format a drive here
as well.

Step 7: Installation Starts. Figure 10: Disk Partition

Figure 11: Installation Starts

Step 8: Before you can start using Windows, there are some personalization, location, browser
and protection, connectivity and error reporting settings that you can adjust (Figure 11)
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Figure 12 : Window Setting


Step 9: If you choose to customize the settings, the first page deals with your contact, calendar,
input, and location data. Read these carefully to decide if you want to turn the settings on or off
as shown in figure 12
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Figure 13 : Customize Setting

Step 10: The next page deals with browser data, connectivity, and error reporting. Again, read
these carefully and toggle the switches accordingly.

Figure 14: Advanced Customize Setting

Step 11: Next, you need to specify who the owner of the device is. You can choose to sign
in with your company ID, which will give you access to your company's resources. Fig 14
illustrates the process.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Step 12: Microsoft really wants you to sign into Windows 10 with your Microsoft account. If

Figure 15 : Ownership

you use Microsoft services like Office, Outlook.com, One Drive, Skype, or Xbox, it makes
sense to sign in with your Microsoft account as it ties them all up and makes your Windows
experience more personal. The complete process is depicted is figure 15.

Figure 16 : Sign in Screen 1

If you use two-factor authentication, you’ll need to enter your code. If you don’t have a
Microsoft account, you can create one right away. Alternatively, you can sign in with a local
account. Unlike Windows 8x, apps like Mail will not force you to switch to a Microsoft
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

account and stop you from using the app if you don’t comply. Figure 16 visualizes the
process.
Step 13: Instead of signing in using your Microsoft account password, you’ve the option to
create and use a short PIN instead.

Figure 17: Creating Microsoft Accounts 1

Step 14: Windows 10 will save new documents and pictures to One Drive. If you’re okay with
that click next to proceed.
Step 15: You can also decide if you want to turn on the Cortana personal assistant feature.
Some people may not want to use Cortana as this allows Microsoft to collect and use their
location, contacts; and more. If you were to ask us, Cortana is one of the best features in
Windows 10. And for it to be truly useful, it must be granted access to such data.At some point,
you'll also be asked if you want to set the built-in apps to be the default apps for certain tasks.
Simply uncheck the checkboxes (Figure 21) for those that you don't want the installer to
change.

Figure 18: signing up


Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Figure 19: Storage Settings

Figure 20: Cortana

Step 16: There's no step 16. Welcome to Windows 10.


Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Figure 20: Setting Apps

Figure 21: Welcome Screen


Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Multi-tasking Operating System.

Windows is multitasking system to be capable of running more than one program at a


time. Most modern machines are designed to be able to handle various programs
which can work together simultaneously (apart from various specifically developed
machines which are designed for use in specific businesses. As with most technology
today, multi-tasking operating systems are constantly evolving, and will continue to
change over time. This is the type of operating system you would find on your
personal computer. It is designed mainly with one user in mind but can handle many
different applications at one time. It must handle running many different programs at
the same time, unlike a Single Use, Single Application operating system. The
memory available is very different to the Single Application operating system. It is
quite normal to have Gigabytes of RAM available on a PC. This is what allows it to
run so many applications at the same time.

Example
The main multi-tasking in operating system is to have the ability to basically use
many different applications run on the computer at the same time. Shown in
Figure 23.

Figure 22: Multitasking example


Lab Outcomes:

 Students will be able to describe the fundamental role and significance of an


operating system in managing hardware and software resources.
 Students will successfully perform the installation of the Windows operating
system, including creating installation media and following the recommended
installation procedures.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

 Students will gain an understanding of multitasking in the operating system and


how it allows for the concurrent execution of multiple tasks, improving overall
system efficiency.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

2
Basic Commands of Disk Operating System

Objectives:

 Introduce students to the basic commands of Disk Operating System (DOS).


 Develop proficiency in using DOS commands for file and directory management.
 Explore advanced DOS commands and system configurations.

DOS Shell usage and its basic commands:

DOS Stands for "Disk Operating System." DOS was the first operating system used by IBM-
compatible computers. DOS uses a command line, or text-based interface, that allows the user to
type commands. By typing simple instructions, the user can browse the files on the hard drive,
open files, and run programs. While the commands are simple to type, the user must know the
basic commands in order to use DOS effectively.

DOS is still included with Windows but is run from the Windows operating system instead of the
other way around. The DOS command prompt can be opened in Windows by selecting "Run..."
from the Start Menu and typing cmd. Some basic commands are discussed below:

Basic Commands:

VER:

This batch command shows the version of MS-DOS you are using.

Syntax:

ver
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Output:

Figure 23: output ver command

ASSOC:

This is a batch command that associates an extension with a file type (FTYPE), displays existing
associations.

Syntax:

ASSOC

Output

Figure 24: Output of ASSOC Commands

CD:

This batch command helps in making changes to a different directory or displays the current directory.

Syntax:
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Cd file path

Output:

Figure 25: output CD command

CLS:

This batch command clears the screen.

Syntax:

cls

Output:

Figure 26 : cls command output

COPY

This batch command is used for copying files from one location to the other.

Syntax:

copy sourceFile destinationFile

copy c:\folder1\file1.doc D:\folder2\file2.doc


Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Output

Figure 27: Output copy Command

DEL:

Figure30: Del command output

This batch command deletes files and not directories.

Syntax:

Del file
path.

Del E:\a.tx

Output:
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Figure 28 : output DIR command

DATE:

This batch command helps to find the system date.

Syntax:

Date Output:

Figure 29: output date command

ECHO:

This batch command displays messages or turns command echoing on or off.

Syntax:

Echo “text”

Output:
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Exit:

This batch command exits the DOS console.

Syntax:

Exit Output:

Figure 30: output echo command

Figure 31: output exit command

Concept of Environment Variables in Windows:

Environment variables:

Environment variables are, in short, variables that describe the environment in which programs run. They
are used by all kinds of programs to answer questions like: What is the name of the computer where I am
installed? What is the name of the user account that is running me? What is my current working
directory? Where is Windows installed? Where are the temporary files stored on this computer? Where is
the OneDrive folder for this user account?

In Windows, environment variables have a name and value. For example, the variable windir (short for
"Windows directory") may have the value "C:\Windows" or another path where Windows is installed.

directories. These directories are set by the different programs that are installed on the computer, and they
vary widely from system to system.

The concept of environment variables exists in most operating systems, from Linux to OS X to Windows.
In principle, they mean the same thing but the way they are implemented and used differs.

Types of environment variables:

There are two types of variables:

User Variables System variables

User Variables:
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

User environment variables have values that differ from user to user. As their name implies, they are
specific to your user account, and they store user specific data, like the location of your user profile, the
folder where temporary files are stored for your account, the location of your One Drive folder, and so on.
They can be edited by that user account but not by other user accounts. These variables can be set by the
user, by Windows or by different programs working with user specific locations.

System variables:

System variables are global and cannot be changed by any user. Their values are the same for all user
accounts. They refer to locations of critical system resources, like the folder where Windows is installed,
the location of Program Files, and so on. These variables are set by Windows, by different programs and
drivers.

How to find the environment variables in Windows:

Viewing the environment variables configured in Windows involves quite a few steps. In Windows 10,
use Cortana’s search box and type environment. Then, click or tap on the “Edit the system environment
variables” search result. If you prefer speaking to Cortana, say “Open environment variables,” and she
will open them for you.The Environment Variables window is opened. There are some minor visual
differences between Windows versions. In the screenshot below you can see how this window looks in
Windows 10.

If you can edit the path, simply click on path and then click edit button the below box will be show add
the path and press ok button

Student Tasks:

Task 1: File and Directory Management Objective: Develop proficiency in using DOS commands for file
and directory management.

Instructions:

 Create a new directory named "LabFiles" on the C: drive.


 Navigate to the "LabFiles" directory using the appropriate command.
 Create three text files: "file1.txt," "file2.txt," and "file3.txt" inside the "LabFiles" directory.
 Use the "DIR" command to verify that the files are created successfully.
 Rename "file3.txt" to "renamed_file.txt."
 Move "renamed_file.txt" to a new subdirectory called "Archive" inside the "LabFiles" directory.
 Use the "COPY" command to make a duplicate of "file1.txt" named "file1_copy.txt" in the same
directory.
 Delete "file2.txt" from the "LabFiles" directory.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

 Use the "DIR" command to ensure that only "file1.txt," "file1_copy.txt," and "renamed_file.txt"
are present in the directory.

Task 2: Disk and System Configuration Objective: Explore advanced DOS commands and system
configurations.

Instructions:

 Use the "CHKDSK" command to check the integrity of the C: drive and fix any errors if found.
 Display the attributes of "file1.txt" using the "ATTRIB" command and take note of the results.
 Use the "EDIT" command to open "file1.txt" and make a simple text edit (e.g., add a new line of
text).
 Save the changes made to "file1.txt" and exit the text editor.
 Use the "MORE" command to display the contents of "file1.txt" on the screen.
 Explore the available system variables by displaying their values using appropriate commands
(e.g., "ECHO %USERNAME%" to show the username).
 Create a batch file named "backup.bat" that copies all the files in the "LabFiles" directory to a
new directory called "Backup" on the D: drive.
 Execute the "backup.bat" batch file and verify that the files are copied to the "Backup" directory.

Lab Outcomes

 Students will demonstrate proficiency in using essential DOS commands for file and directory
management, including creating, copying, renaming, moving, and deleting files and directories.
 Students will be able to perform disk and system configurations using advanced DOS commands,
such as checking disk integrity, displaying file attributes, and utilizing system variables.
 Students will showcase their ability to create and execute batch files for automating repetitive
tasks, fostering a deeper understanding of the benefits and applications of batch scripting in DOS.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

3
Understanding and implementation of Basic System calls.

Introduction

A system call is just what its name implies—a request for the operating system to
do something on behalf of the user’s program.
 open()
 read()
 write()
 close()
 wait()
 fork()
 exec()

Objectives

 To be familiar with system calls.


 To be able to use system calls.
 To be able to read/write.
 To be able to open/close.
 To be able to fork and execute.

1. open():
The `open()` system call is used to open a file or create a new file if it doesn't already exist. It
takes a file name and various parameters as arguments, such as the file access mode (read, write,
or both) and permissions. The `open()` call returns a file descriptor, which is a unique identifier
representing the opened file. This descriptor is used in subsequent read and write operations on
the file.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

2. read():
The `read()` system call is used to read data from an open file. It takes the file descriptor, a
buffer where the data will be stored, and the number of bytes to read as arguments. The `read()`
call reads the specified number of bytes from the file into the buffer and advances the file pointer
accordingly. It returns the number of bytes actually read, which may be less than the requested
number if the end of the file is reached.

3. write():
The `write()` system call is used to write data to an open file. It takes the file descriptor, a buffer
containing the data to be written, and the number of bytes to write as arguments. The `write()`
call writes the specified number of bytes from the buffer to the file at the current file pointer
position. It returns the number of bytes actually written, which may be less than the requested
number if there is an error during the write operation.

4. close():
The `close()` system call is used to close an open file. It takes the file descriptor of the file to be
closed as an argument. The `close()` call releases the resources associated with the file, flushes
any unwritten data to the disk, and updates the file's metadata. After closing a file, its file
descriptor becomes invalid and cannot be used for further operations on the file.

5. wait():
The `wait()` system call is used by a parent process to wait for the termination of its child
process. When a child process exits, its termination status is saved by the system until the parent
calls `wait()`. The `wait()` call suspends the execution of the parent process until a child process
terminates. It also provides information about the terminated child process, such as its exit status.

6. fork():
The `fork()` system call is used to create a new process by duplicating the existing process. The
new process, known as the child process, is an exact copy of the parent process, except for some
attributes like the process ID. After a successful `fork()`, the parent and child processes continue
execution from the point of the `fork()` call but with different process IDs. The `fork()` call
returns different values in the parent and child processes, allowing them to differentiate between
each other.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

7. exec():
The `exec()` system call is used to replace the current process with a new process. It loads a new
executable file into the current process's memory and starts its execution. The `exec()` call is
typically used after a successful `fork()` to execute a different program in the child process. It
loads the new program's code and initializes its memory, stack, and file descriptors. Once the
`exec()` call is made, the current process is replaced entirely, and the new program starts
executing from its entry point.

These system calls provide essential functionalities for interacting with files, managing
processes, and executing programs in an operating system.

Implementation of open(), read(), write() and close() functions:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
//necessary header files
#define BUFFER_SIZE 80

int main()
{
int fd; // File descriptor , File descriptors are non-negative integers, where the value -1 is often used
to indicate an error condition.

char buffer[BUFFER_SIZE];
static char message[] = "Hello, world";
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

// Open the file for read/write access (or create it if it doesn't exist)
fd = open("myfile.txt", O_RDWR | O_CREAT, 0644);

//The file permissions are set to 0644, which allows read and write access for the owner and read-only
access for others.

if (fd != -1)
{
printf("myfile opened for read/write access\n");

// Write the message to the file


if (write(fd, message, sizeof(message)) == -1)
{
printf("Error writing to myfile\n");
close(fd);
return 1;
}

// Seek back to the beginning of the file


if (lseek(fd, 0, SEEK_SET) == -1)
{
printf("Error seeking to the beginning of the file\n");
close(fd);
return 1;
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

// Read the contents from the file


if (read(fd, buffer, sizeof(message)) == -1)
{
printf("Error reading from myfile\n");
close(fd);
return 1;
}

printf("%s was written to myfile\n", buffer);

// Close the file


if (close(fd) == -1)
{
printf("Error closing myfile\n");
return 1;
}
}
else
{
printf("Error opening myfile\n");
return 1;
}

return 0;
}
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Implementing fork system call using C program

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
pid_t pid;

//The pid_t data type is a signed integer type


which is capable of representing a process ID

pid = fork();

if (pid == 0)
{
printf("I'm the child process\n");
}
else if (pid > 0)
{
printf("I'm the parent process. My child pid is %d\n", pid);
}
else
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

{
perror("Error in fork");
return 1;
}

return 0;
}
wait()
The wait system call suspends the calling process until one of its immediate children terminates.
If the call is successful, the process ID of the terminating child is returned.

Zombie process—a process that has terminated but whose exit status has not yet
been received by its parent process. The process will remain in the operating system’s
process table as a zombie process, indicating that it is not to be scheduled for further
execution.

But that it cannot be completely removed (and its


process ID cannot be reused) pid_t wait(int *status);
Where status is an integer value where the UNIX system stores the value returned by child
process.

Implementing wait system call using C program

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main()
{
pid_t pid;
int status;

pid = fork();
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

if (pid == -1)
{
printf("fork failed\n");
exit(1);
}

if (pid == 0)
{
/* Child */
printf("Child here!\n");
}
else
{
/* Parent */
wait(&status);
printf("Well done, kid!\n");
}

return 0;
}

Implementation Task 1:

Objective: To write university card details to a text file using the write system call and read the
contents of the file using the read system call.

Write Card Details:

Open a text file using the open system call with appropriate permissions.

If the file cannot be opened, handle the error by displaying an error message and exiting the
program.

Use the write system call to write the university card details to the file.

Close the file using the close system call.

Read File Contents:

Open the same text file using the open system call.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

If the file cannot be opened, handle the error by displaying an error message and exiting the
program.

Use the read system call to read the contents of the file into a buffer.

Display the contents of the buffer to verify the successful reading of the file.

Close the file using the close system call.

Implementation Task 2:

Objective: To start a process and create its child processes, and then display the details of these
processes using system calls.

Process Creation:

Use the fork system call to create a child process from the parent process.

Check the return value of fork to determine whether the process is the parent or the child.

For the parent process, display the process details including the process ID using the getpid
system call.

For the child process, display the process details including the process ID and the parent process
ID using the getpid and getppid system calls.

Display Process Details:

Iterate over the created child processes and repeat the process details display.

Use appropriate system calls to retrieve the process IDs and parent process IDs.

Format and display the process details using printf or a similar function.

Note: It's important to handle errors appropriately by checking the return values of system calls
and displaying error messages when necessary. Additionally, closing any opened files using the
close system call is essential to release system resources.

Lab Outcomes:

 System Call Familiarity: Students will become familiar with various system calls,
including open (), read(), write(), close(), fork(), and exec(). They will understand the
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

purpose and usage of these system calls, enabling them to interact with the operating
system and perform essential operations such as file handling and process management.
 System Call Implementation: Students will demonstrate their ability to use system calls
effectively to read and write data from/to files, manage processes, and execute new
programs. They will successfully implement the required functionalities in their
programs, showcasing their understanding of system call syntax and usage.
 Troubleshooting and Error Handling: Students will develop skills in identifying and
handling potential errors that may arise when working with system calls. They will be
able to use error-checking mechanisms, such as checking return values and displaying
appropriate error messages, to ensure robustness and reliability in their programs.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

4
Installation of VMware and Linux and understanding basics of Linux
Operating System

Objectives:

 Objective 1: Install VMware and Linux Operating System.


 Objective 2: Familiarize students with the basics of the Linux Operating System.
 Objective 3: Perform basic tasks and system management in the Linux Operating System

Experiment Requirements:

1. Computer Systems/Laptop Requirement


a. 20 GB of available hard disk memory
b. 4GB RAM
c. 2.3 GHz processor
2. Operating System Requirement
a. Windows 7, 8, 10
b. Mac OS
c. Linux/Unix
3. Universal Serial Bus (USB)

Description:

What is VMware?

To understand VMware you must know what is Virtualization. VMware is a company which
provide Virtualization on Desktops.

Virtualization
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Virtualization is the creation of a virtual; rather than actual version of something, such as an
operating system, a server, a storage device or network resources.

You probably know a little about virtualization if you have ever divided your hard drive into
different partitions. A partition is the logical division of a hard disk drive to create, in effect, two
separate hard drives.

In Another Words;

In computing, virtualization means to create a virtual version of a device or resource, such as a


server, storage device, network or even an operating system where the framework divides the
resource into one or more execution environments.

Key Properties of Virtual Machines:

VMs have the following characteristics, which offer several benefits.

Partitioning

 Run multiple operating systems on one physical machine.

 Divide system resources between virtual machines.

Isolation

 Provide fault and security isolation at the hardware level.

 Preserve performance with advanced resource controls.

Encapsulation

 Save the entire state of a virtual machine to files.

 Move and copy virtual machines as easily as moving and copying files.

Step By Step Process:

Step 1: Download VMware from VMware website

https://www.vmware.com
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Step 2: Download Linux Ubuntu version

https://ubuntu.com

Step 3: Installation of VMware

 Run the installer. Start the installer by double clicking it.


 Custom setup – Enhanced Keyboard driver and Installation directory.
 User Experience Settings.
 Select where the shortcuts will be installed.
 Ready to install.
 License

Step 4: Installation of Ubuntu

Once you have installed VMware, next step is to install Ubuntu version of Linux. Follow the
following steps to install Ubuntu.

 Open VMware software.

 Click on create new virtual machine


 Select the folder to install Ubuntu
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

 Set username and password

 Select the folder where Ubuntu image is placed and click next
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

 Now the Ubuntu will install.

Step 5: After installation you can open Ubuntu installation from VMware by clicking on open
virtual machine. Now you can browse the directories of Ubuntu and explore the Linux OS.

Extra Remarks:

 You can also install Ubuntu as a separating operating system, but virtual machine is a
better option.
 Beside VMware there are some other virtual machines available, e.g., you can use Oracle
Virtual Box

Outcomes:

 Students will successfully install VMware virtualization software on their computers and
create a virtual machine (VM) to run the Linux Operating System.
 Students will demonstrate a basic understanding of the Linux Operating System,
including familiarity with the Linux file system hierarchy, essential command-line
operations, and user and group management.
 Students will acquire practical skills in performing basic tasks and system management in
the Linux Operating System, such as file manipulation, software package installation, and
system updates using package managers.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

5
Basic Commands of Linux Operating System

Objectives:

 Familiarize students with the Linux/Unix operating system and its command-line
interface.
 Provide students with hands-on experience in executing basic Linux commands for
system management and file operations.
 Enable students to understand and utilize filters and pipes to manipulate and process data
efficiently in the Linux environment.

Experiment Requirements:

 Virtual Machine VMware/Virtual Box


 Ubuntu or any other installation of Linux OS

Description:

Linux includes a large number of commands, but we’ve chosen some of the most important ones
to present here. Learn these commands, and you’ll be much more at home at the Linux command
prompt. Linux commands are a better way to operate the operating system and perform
administrative tasks.

Step by step Process:

Step 1: Open Ubuntu in Virtual Machine.

Step 2: You will be on the desktop on your Linux OS. Search for terminal in search bar. OR you
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Step 3: Write and practice following commands on terminal can open it by pressing.
Ctrl+Alt+T keys.

Executing Commands:

Date Command:
This command is used to display the current data and time.
Syntax:
$date
$date +“%c”
Options : -
a = Abbreviated weekday.
A = Full weekday.
b = Abbreviated month.
B = Full month.
c = Current day and time.
C = Display the century as a decimal number.
d = Day of the month.
D = Day in „mm/dd/yy‟ format
h = Abbreviated month day.
H = Display the hour.
L = Day of the year.
m = Month of the year.
M = Minute.
P = Display AM or PM
S = Seconds
T = HH:MM:SS format
u = Week of the year.
y = Display the year in 2 digit.
Y = Display the full year.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Z = Time zone .
To change the format :
Syntax :
$date „+%H-%M-%S‟

Calendar Command:
This command is used to display the calendar of the year or the particular month of
calendar year.
Syntax:
a.$cal <year>
b.$cal <month> <year>
Here the first syntax gives the entire calendar for given year & the second Syntax gives
the calendar of reserved mon th of that year.

Echo Command:
This command is used to print the arguments on the screen .
Syntax : $echo <text>

Multi line echo command:


To have the output in the same line , the following commands can be used.
Syntax: $echo text\ text
To have the output in different line, the following command can be used.
Syntax: $echo -e “text \n text2 \n text3”
.Banner Command:
It is used to display the arguments in „#‟ symbol .
Syntax : $banner <arguments> e,g banner yourname
’who’ Command:
It is used to display who are the users connected to our computer currently.
Syntax: $who – option‟s
Options : -
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

H–Display the output with headers.


b–Display the last booting date or time or when the system was lastely rebooted.
’who am i’ Command:
The who am i command is used to display the information of the current logged-in user.
It provides details such as the username.
Syntax : $who am i (withoutspace)
’tty’ Command:
It will display the terminal name.
Syntax : $tty

’Binary’ Calculator Command:


It will change the „$‟ mode and in the new mode, arithmetic operations such as +,-
,*,/,%,sqrt(),length(),=, etc can be performed . This command is used to go to the binary
calculus mode.
Syntax:
$bc operations
^d
$
1 base –input base
0 base – output base are used for base conversions.
Base:
Decimal = 1 Binary = 2 Octal = 8 Hexa = 1

echo “ibase = 10; obase = 10; 5+6” | bc


’CLEAR’ Command:
It is used to clear the screen.
Syntax : $clear

’MAN’ Command:
It help us to know about the particular command and its options & working. It is like
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

help‟ command in windows .


Syntax : $man <command name> man mkdir

Manipulation Command:
It is used to manipulate the screen.
Syntax: $tput <argument>
Arguments :
1.Clear – to clear the screen.
2.Longname – Display the complete name of the terminal.
3.SMSO – background become white and foreground become black color.
4.rmso – background become black and foreground becomes white color.
5.Cop R C – Move to the cursor position to the specified location.
6.Cols – Display the number of columns in our terminals.

LIST Command:
It is used to list all the contents in the current working directory.
Syntax: $ ls – options <arguments>
If the command does not contain any argument means it is working in the
Current directory.
Options:
a– used to list all the files including the hidden files.
c– list all the files column wise.
d- list all the directories.
m- list the files separated by commas.
p- list files include „/‟ to all the directories.
r- list the files in reverse alphabetical order.
f- list the files based on the list modification date.
x-list in column wise sorted order.

Directory related commands:


Mirpur University of Science & Technology, MUST Mirpur
AJ&K

a. Present Working Directory Command:


To print the complete path of the current working directory.
Syntax : $pwd
b. MKDIR Command:
To create or make a new directory in a current directory.
Syntax : $mkdir <directory name>
c. CD Command:
To change or move the directory to the mentioned directory .
Syntax: $cd <directory name.
d. RMDIR Command:
To remove a directory in the current directory & not the current directory itself.
Syntax : $rmdir <directory name>

File related commands :

Create a file:
To create a new file in the current directory we use CAT command.
Syntax:
$cat > <filename.
The > symbol is directory we use cat command.
touch myfile.txt also used

Display a file:
To display the content of file mentioned we use CAT command without „>‟ operator.
Syntax:
$cat <filename.
Options –s = to neglect the warning /error message.

Copying contents:
To copy the content of one file with another. If file does not exist, a new file is created
and if the file exists with some data then it is overwritten.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Syntax:
$ cat <filename source> >> <destination filename>
$ cat <source filename> >> <destination filename> it is avoid
overwriting.
Options :-
-n content of file with numbers included with blank lines.
Syntax :
$cat –n <filename>

Sorting a file:
To sort the contents in alphabetical order in reverse order.
Syntax :
$sort <filename >
Option : $ sort –r <filename>

Copying contents from one file to another:


To copy the contents from source to destination file . so that both contents are same.
Syntax :
$cp <source filename> <destination filename>
$cp <source filename path > <destination filename path>

MOVE Command:
To completely move the contents from source file to destination file and to remove the
source file.
Syntax :
$ mv <source filename> <destination filename>

REMOVE Command:
To permanently remove the file we use this command.
Syntax :
$rm <filename>
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

WORD Command:
To list the content count of no of lines, words, characters.
Syntax:
$wc<filename>
Options :
-c – to display no of characters.
-l – to display only the lines.
-w – to display the no of words.

PAGE Command:
This command is used to display the contents of the file page wise & next page can be
viewed by pressing the enter key.
Syntax :
$pg <filename>

FILTERS AND PIPES


HEAD: It is used to display the top ten lines of file.
Syntax: $head<filename>
TAIL : This command is used to display the last ten lines of file.
Syntax: $tail<filename>
PAGE : This command shows the page by page a screenfull of information is displayed after
which the page command displays a prompt and passes for the user to strike the enter key to
continue scrolling.
Syntax: $ls –a\p
MORE: It also displays the file page by page .To continue scrolling with more command ,
press the space bar key.
Syntax: $more<filename>
SORT : This command is used to sort the data in some order.
Syntax: $sort<filename>
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

PIPE : It is a mechanism by which the output of one command can be channeled into the input
of another command.
Syntax: $who | wc-l
TR :The tr filter is used to translate one set of characters from the standard inputs to another.
Syntax: $tr “[a-z]” “[A-Z]”

Outcomes:

 Students will demonstrate proficiency in navigating and interacting with the Linux
command-line interface, enhancing their ability to work efficiently in a Linux
environment.
 Students will be able to execute basic Linux commands for tasks such as displaying the
date, creating directories, listing file contents, copying and moving files, and performing
file-related operations.
 Students will grasp the concept of filters and pipes in Linux, allowing them to use these
powerful tools to manipulate data and streamline complex tasks, ultimately increasing
their productivity in working with the Linux operating system.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

6
Implementation of First Come First Served (FCFS) CPU scheduling
algorithm.

Part a:

Experiment Requirement:

Linux/Windows OS

C/C++ editor/compiler

Objectives:

 To Simulate the FCFS CPU scheduling algorithm using C/C++ programming.


 To Implement the FCFS algorithm to calculate waiting time, turnaround time, and other
process-related metrics.
 To Understand the process of arranging processes in the order of their arrival and
calculate their execution times.

Algorithm:

1. Create an array to store the process names (pn), arrival times (arr), and burst times (bur).
2. Sort the processes based on their arrival times in ascending order.
3. Initialize the waiting time of the first process as 0 and its total time as its starting time
(star).
4. Calculate the total time and processing time for the remaining processes using the burst
times.
5. Set the waiting time of each process as the total time of the previous process.
6. Calculate the total time of each process by adding the waiting time and the service time
(burst time).
7. Calculate the total waiting time by adding the waiting times of all processes.
8. Calculate the total turnaround time by adding the total times of all processes.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

9. Calculate the average waiting time by dividing the total waiting time by the total number
of processes.
10. Calculate the average turnaround time by dividing the total turnaround time by the
number of processes.
11. Display the result.

Source code:

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main() {
string pn[10], t;
int arr[10], bur[10], star[10], finish[10], tat[10], wt[10], n, temp;
int totwt = 0, tottat = 0;

cout << "Enter the number of processes: ";


cin >> n;

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


cout << "Enter the Process Name, Arrival Time & Burst Time: ";
cin >> pn[i] >> arr[i] >> bur[i];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

if (arr[i] < arr[j]) {


temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;

temp = bur[i];
bur[i] = bur[j];
bur[j] = temp;

t = pn[i];
pn[i] = pn[j];
pn[j] = t;
}
}
}

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


if (i == 0)
star[i] = arr[i];
else
star[i] = finish[i - 1];

wt[i] = star[i] - arr[i];


finish[i] = star[i] + bur[i];
tat[i] = finish[i] - arr[i];
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

totwt += wt[i];
tottat += tat[i];
}

cout << "\nPName\tArrtime\tBurtime\tWaitTime\tStart\tTAT\tFinish" << endl;


for (int i = 0; i < n; i++) {
cout << pn[i] << "\t" << arr[i] << "\t" << bur[i] << "\t" << wt[i] << "\t" << star[i] << "\t" <<
tat[i] << "\t" << finish[i] << endl;
}

float avgWaitingTime = (float)totwt / n;


float avgTurnaroundTime = (float)tottat / n;
cout << "Average Waiting time: " << avgWaitingTime << endl;
cout << "Average Turn Around Time: " << avgTurnaroundTime << endl;

return 0;
}
Sample Inputs & Outputs:

Input:

Enter the number of processes: 3

Enter the Process Name, Arrival Time & Burst Time: p1 2 4

Enter the Process Name, Arrival Time & Burst Time: p2 3 5

Enter the Process Name, Arrival Time & Burst Time: p3 1 6


Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Output:

PName Arrtime Burtime WaitTime Start TAT Finish

p3 1 6 0 1 6 7

p1 2 4 1 7 5 12

p2 3 5 3 12 8 20

Average Waiting time: 1.33333

Average Turn Around Time: 6.33333

Student Task: Implement the FCFS CPU scheduling algorithm in C/C++ to schedule a set of
processes based on their arrival times and burst times.

Outcomes:

1. Students will be able to understand the concept of the FCFS CPU scheduling algorithm
and its implementation in a programming language.
2. Students will be proficient in calculating waiting times and turnaround times for
processes scheduled using FCFS.
3. Develop problem-solving skills to organize and manage processes in an orderly manner,
which is crucial for effective CPU scheduling.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

7
Implementation of Shortest Job First (SJF) CPU scheduling algorithm

Objectives:

 To Simulate the SJF CPU scheduling algorithm using C/C++ programming.


 To Implement the SJF algorithm to calculate waiting time, turnaround time, and other
process-related metrics.
 To Understand the process of selecting processes with the shortest burst time first.

Algorithm:

1. Declare arrays for process names (pn), arrival times (at), and execution times (et).
2. Sort the processes based on their execution times in ascending order.
3. Calculate the waiting time (wt) and turnaround time (ta) for each process based on their
execution times and arrival times.
4. Calculate the total waiting time (totwt) and total turnaround time (totta).
5. Calculate the average waiting time (awt) and average turnaround time (ata).
6. Display the result.

Source Code

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main() {
int et[20], at[10], n, i, j, temp, st[10], ft[10], wt[10], ta[10];
float awt, ata;
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

string pn[10], t;

cout << "Enter the number of processes: ";


cin >> n;

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


cout << "Enter process name, arrival time & execution time: ";
cin >> pn[i] >> at[i] >> et[i];
}

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


for (j = 0; j < n; j++) {
if (et[i] < et[j]) {
temp = at[i];
at[i] = at[j];
at[j] = temp;

temp = et[i];
et[i] = et[j];
et[j] = temp;

t = pn[i];
pn[i] = pn[j];
pn[j] = t;
}
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

}
}

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


if (i == 0)
st[i] = at[i];
else
st[i] = ft[i - 1];
wt[i] = st[i] - at[i];
ft[i] = st[i] + et[i];
ta[i] = ft[i] - at[i];
}

int totwt = 0, totta = 0;


for (i = 0; i < n; i++) {
totwt += wt[i];
totta += ta[i];
}

awt = (float)totwt / n;
ata = (float)totta / n;

cout << "\nPname\tarrivaltime\texecutiontime\twaitingtime\ttatime" << endl;


for (i = 0; i < n; i++) {
cout << pn[i] << "\t" << at[i] << "\t\t" << et[i] << "\t\t" << wt[i] << "\t\t" << ta[i] << endl;
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

}
cout << "Average waiting time is: " << awt << endl;
cout << "Average turnaround time is: " << ata << endl;

return 0;
}
Input:
Enter the number of processes: 3
Enter process name, arrival time & execution time: p1 4 6
Enter process name, arrival time & execution time: p2 5 15
Enter process name, arrival time & execution time: p3 6 11

Output:
Pname arrivaltime executiontime waitingtime tatime
p1 4 6 0 6
p3 6 11 4 15
p2 5 15 16 31

Average waiting time is: 6.66667


Average turnaround time is: 17.3333
Student Task: Implement the SJF CPU scheduling algorithm in C/C++ to schedule a set of
processes based on their burst times.

Outcomes:
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

1. Students will gain a comprehensive understanding of the SJF CPU scheduling algorithm
and its practical implementation in C/C++.
2. Students will be proficient in calculating waiting times and turnaround times for
processes scheduled using the SJF algorithm.
3. Students will develop critical thinking skills to prioritize processes based on execution
times, leading to efficient CPU scheduling in real-world scenarios
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

8
Implementation of Round Robin algorithm

Introduction:

In this lab, Students will learn about the Round Robin (RR) CPU scheduling algorithm, which is
one of the most widely used scheduling algorithms in operating systems. RR is a preemptive
algorithm that assigns each process a fixed time unit called the time quantum. It then switches
between processes in a circular queue fashion, giving each process an equal amount of time
before moving to the next one.

Objectives:

 To understand the concept of CPU scheduling and the need for scheduling algorithms.
 To Implement the Round Robin CPU scheduling algorithm in C/C++.
 To Simulate the scheduling of processes using Round Robin with a fixed time quantum.

Experiment Requirements:

Linux/Windows Operating System

C/C++ editor/compiler (e.g., Code::Blocks, Visual Studio, or any other preferred IDE)

Algorithm:

1. Declare the array size.


2. Get the number of processes to be inserted (n).
3. Get the time quantum (ts) from the user (e.g., between 10 to 100ms).
4. Declare the required arrays:
5. et[30 An array to store estimated execution times for each process.
6. pn[10][10]: A 2D array to store process names.
7. x: A variable to track the total time elapsed.
8. tot: A variable to store the total estimated time for all processes.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

9. Input the process name and estimated execution time for each process.
10. Display the list of processes with their corresponding names and estimated times.
11. Calculate the total estimated time (tot) by adding the estimated execution times of all
processes.

Implementation:

#include <iostream>

#include <string>

using namespace std;

int main() {

int et[30], ts, n, i, x = 0, tot = 0;

string pn[10];

cout << "Enter the number of processes: ";

cin >> n;

cout << "Enter the time quantum: ";

cin >> ts;

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

cout << "Enter process name & estimated time: ";

cin >> pn[i] >> et[i];

cout << "The processes are:\n";

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

cout << "Process " << i + 1 << ": " << pn[i] << endl;
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

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

tot += et[i];

cout << "\nExecution Sequence:\n";

while (x != tot) {

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

if (et[i] > ts) {

x += ts;

cout << pn[i] << " -> " << ts << endl;

et[i] -= ts;

} else if ((et[i] <= ts) && et[i] != 0) {

x += et[i];

cout << pn[i] << " -> " << et[i] << endl;

et[i] = 0;

cout << "\nTotal Estimated Time: " << x << endl;

return 0;

Sample Input

Enter the number of processes: 3

Enter the time quantum: 4


Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Enter process name & estimated time: P1 10

Enter process name & estimated time: P2 5

Enter process name & estimated time: P3 7

Sample Output

The processes are:

Process 1: P1

Process 2: P2

Process 3: P3

Execution Sequence:

P1 -> 4

P2 -> 4

P3 -> 4

P1 ->

P3 -> 3

P1 -> 1

Total Estimated Time: 18

Students Task: To implement and simulate the Round Robin CPU scheduling algorithm in C++,
and validate its functionality with different inputs.

Outcomes:

 Students will gain a better understanding of the Round Robin CPU scheduling algorithm
by implementing it in C++ and exploring its working principles.
 Students will develop proficiency in coding and problem-solving through hands-on
experience with C++ programming, specifically in the context of implementing
algorithms like Round Robin CPU scheduling.
 By identifying and resolving any issues or errors in the code, students will strengthen
their logical reasoning abilities and improve their skills in debugging and
troubleshooting.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

9
File allocation strategies - Sequential File Allocation

Objectives:

 Students will implement the sequential file allocation technique to manage disk storage
efficiently.
 Students will understand the concept of sequential file allocation and its practical
application in disk management.

Experiment Requirements:

Linux/Windows OS

C/C++ editor/compiler

Algorithm:

Step 1: Start the program.


Step 2: Get the number of files.
Step 3: Get the memory requirement of each file.
Step 4: Allocate the required locations to each in sequential order.
a) Randomly select a location from available locations: st = random(100);
b) Check whether the required locations are free from the selected location.
c) Allocate and set flag=1 to the allocated locations.
Step 5: Print the results: file number, length, and blocks allocated.
Step 6: Stop the program.

Source Code (C++):

#include <iostream>

using namespace std;


Mirpur University of Science & Technology, MUST Mirpur
AJ&K

int main() {

int f[50], i, st, j, len, c;

for (i = 0; i < 50; i++)

f[i] = 0;

do {

cout << "\nEnter the starting block & length of file: ";

cin >> st >> len;

for (j = st; j < (st + len); j++) {

if (f[j] == 0) {

f[j] = 1;

cout << j << "->" << f[j] << endl;

} else {

cout << "Block already allocated" << endl;

break;

if (j == (st + len))

cout << "The file is allocated to disk" << endl;

cout << "\nIf you want to enter more files? (1-Yes/0-No): ";

cin >> c;

} while (c == 1);
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

return 0;

Output:

Enter the starting block & length of file: 4 10

4->1

5->1

6->1

7->1

8->1

9->1

10->1

11->1

12->1

13->1

The file is allocated to disk

If you want to enter more files? (1-Yes/0-No): 0

Part b: Linked File Allocation

Objectives:

 Students will implement the linked file allocation technique to efficiently manage disk storage for
large files.
 They will understand the concept of linked file allocation and its advantages in handling large
files.

Experiment Requirements:
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Linux/Windows OS

C/C++ editor/compiler

Algorithm:
Step 1: Start the program.
Step 2: Get the number of blocks that are already allocated.
Step 3: Get the blocks' numbers that are already allocated.
Step 4: Enter the starting index block and length for the new file.
Step 5: Check whether the selected location is free.
Step 6: If the location is free, allocate and set flag = 1 to the allocated locations.
Step 7: Print the results: file number, length, and blocks allocated.
Step 8: Stop the program.

Source Code (C++):

#include <iostream>

using namespace std;

int main() {

int f[50], p, i, j, k, a, st, len, n, c;

for (i = 0; i < 50; i++)

f[i] = 0;

cout << "Enter how many blocks are already allocated: ";

cin >> p;

cout << "Enter the block numbers that are already allocated: ";

for (i = 0; i < p; i++) {

cin >> a;

f[a] = 1;

}
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

do {

cout << "Enter the starting index block & length: ";

cin >> st >> len;

k = len;

for (j = st; j < (k + st); j++) {

if (f[j] == 0) {

f[j] = 1;

cout << j << "->" << f[j] << endl;

} else {

cout << j << "->File is already allocated" << endl;

k++;

cout << "If you want to enter one more file? (1-Yes/0-No): ";

cin >> c;

} while (c == 1);

return 0;

Output:

Enter how many blocks are already allocated: 3

Enter the block numbers that are already allocated: 4 7 9

Enter the starting index block & length: 3 1

3->1
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Enter one more file? (1-Yes/0-No): 1

Enter the starting index block & length: 5 3

5->1

6->1

7->File is already allocated

8->1

Enter one more file? (1-Yes/0-No): 0

Outcomes:

 Students will gain knowledge of implementing sequential and linked file allocation techniques in
C++.
 They will be able to understand and analyze the benefits and limitations of each file allocation
technique in disk management.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

10
Understanding and Implementation of File allocation strategies-
Indexed file allocation

Objective:
To implement the indexed file allocation technique in C/C++.
Experiment Requirements:
Linux/Windows OS
C/C++ editor/compiler
Algorithm:
1. Start the program.
2. Initialize the array f to keep track of allocated blocks (set all elements to 0).
3. Get the index block from the user.
4. Check if the index block is already allocated (f[index] == 0).
5. If not allocated, set f[index] to 1 and proceed.
6. If already allocated, print "Block already allocated" and go back to step 3.
7. Get the number of files (n) on the index block.
8. For each file in the index block, get the block number and store it in the inde array.
9. Check if any of the blocks in the inde array are already allocated (f[inde[i]] == 1).
10. If any block is already allocated, print "Block already allocated" and go back to step 3.
11. Mark all the blocks in the inde array as allocated (set f[inde[i]] to 1).
12. Print "Allocated" and "File indexed".
13. Display the details of each file: index block -> file block : allocated flag.
14. Ask the user if they want to enter more files (1 for Yes, 0 for No).
 If Yes, go back to step 3.
 If No, exit the program.
Source Code:
#include <iostream>
using namespace std;
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

int f[50], i, j, inde[50], n, c, p;


int main() {
for (i = 0; i < 50; i++)
f[i] = 0;
x:
cout << "Enter index block: ";
cin >> p;
if (f[p] == 0) {
f[p] = 1;
cout << "Enter no of files on index: ";
cin >> n;
} else {
cout << "Block already allocated" << endl;
goto x;
}
cout << "Enter the file block numbers:" << endl;
for (i = 0; i < n; i++)
cin >> inde[i];

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


if (f[inde[i]] == 1) {
cout << "Block already allocated" << endl;
goto x;
}
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

for (j = 0; j < n; j++)


f[inde[j]] = 1;

cout << "\nAllocated" << endl;


cout << "File indexed" << endl;

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


cout << p << "->" << inde[i] << ":" << f[inde[i]] << endl;

cout << "Enter 1 to enter more files and 0 to exit: ";


cin >> c;

if (c == 1)
goto x;
else
return 0;
}
Output

Enter index block: 9

Enter no of files on index: 3

123

Allocated

File indexed
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

9->1:1

9->2:1

9->3:1

Enter 1 to enter more files and 0 to exit: 0

Students Task:

Modify the existing C/C++ program to include error handling for invalid user inputs. If the user
enters an invalid input (e.g., non-integer values for block numbers), display an appropriate error
message and ask the user to enter the input again. Implement this error handling for both the
index block and the file block numbers.

Outcomes:

 The program successfully executes the indexed file allocation technique.


 Students have learned how to simulate indexed file allocation using the C++
programming language.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

11
Understanding and implementation File allocation strategies-
linked file allocation
Objectives:

Students will implement the linked file allocation technique to efficiently manage disk storage
for large files.

They will understand the concept of linked file allocation and its advantages in handling large
files.

Experiment Requirements:

Linux/Windows OS

C/C++ editor/compiler

Algorithm:

1. Start the program.


2. Initialize the file allocation array f with 0, indicating all blocks are initially free.
3. Ask the user to enter the number of blocks that are already allocated and their block
numbers.
4. Enter the starting index block and length for the new file.
5. Check if each block in the range of the new file is already allocated. If not, allocate the
block and proceed.
6. Display the file allocation information for the new file.
7. Ask the user if they want to enter more files. If yes, go to step 4.
8. If the user does not want to enter more files, exit the program.

Source Code (C++):

#include <iostream>

using namespace std;

int main() {
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

int f[50], p, i, j, k, a, st, len, n, c;

for (i = 0; i < 50; i++)

f[i] = 0;

cout << "Enter how many blocks are already allocated: ";

cin >> p;

cout << "Enter the block numbers that are already allocated: ";

for (i = 0; i < p; i++) {

cin >> a;

f[a] = 1;

do {

cout << "Enter the starting index block & length: ";

cin >> st >> len;

k = len;

for (j = st; j < (k + st); j++) {

if (f[j] == 0) {

f[j] = 1;

cout << j << "->" << f[j] << endl;

} else {

cout << j << "->File is already allocated" << endl;

k++;

cout << "Enter one more file? (1-Yes/0-No): ";

cin >> c;

} while (c == 1);
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

return 0;

Output:

Enter how many blocks are already allocated: 3


Enter the block numbers that are already allocated: 4 7 9
Enter the starting index block & length: 3 1
3->1
Enter one more file? (1-Yes/0-No): 1
Enter the starting index block & length: 5 3
5->1
6->1
7->File is already allocated
8->1
Enter one more file? (1-Yes/0-No): 0

Students Task:
Write a C++ program to implement the linked file allocation technique. The program should
follow the given algorithm and allow the user to allocate blocks for a new file using linked
allocation. Display the allocated blocks for the new file along with their block numbers.

Outcomes:

 Students will gain practical knowledge of implementing linked file allocation technique
in C++.
 They will be able to understand and analyze the benefits and limitations of linked file
allocation in disk management.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

12
Implementation Producer-Consumer Problem using Semaphores (C++)

The Producer-Consumer Problem is a classic synchronization challenge that arises when


multiple processes need to share a common resource, like a fixed-size buffer. It involves two
types of processes: producers and consumers, which interact with the shared buffer to exchange
data or items.

In this lab, we will explore the complexity of the Producer-Consumer Problem and its
significance in concurrent programming. We will learn about the challenges faced by producers
and consumers when working concurrently and the importance of proper synchronization to
avoid issues like data corruption, buffer overflow, or deadlock.

Objectives:

To understand the producer-consumer problem and the challenges associated with


synchronization in a multi-threaded environment.

To implement the producer-consumer problem using semaphores in C++ to ensure proper


synchronization between producer and consumer threads.

Experiment Requirements:

Linux/Windows OS

C++ editor/compiler

Algorithm:

1. Declare necessary variables for producer and consumer threads using std::thread.
2. Define a structure to hold the shared buffer and create a semaphore variable.
3. Read the number of items to be produced and consumed from the user.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

4. Define functions for creating and destroying semaphores.


5. Define the producer function to add items to the buffer.
6. Define the consumer function to consume items from the buffer.
7. Implement synchronization using semaphores to avoid race conditions.
8. Test the program by running producer and consumer threads concurrently.
9. Stop the execution of threads.

Source Code: (Producer-Consumer Problem)

#include <iostream>

#include <thread>

#include <mutex>

#include <condition_variable>

using namespace std;

const int bufsize = 10;

int buffer[bufsize], in = 0, out = 0;

mutex mtx;

condition_variable not_full, not_empty;

void producer(int produce) {

unique_lock<mutex> lock(mtx);

not_full.wait(lock, [] { return (in + 1) % bufsize != out; });

buffer[in] = produce;

in = (in + 1) % bufsize;

not_empty.notify_one();

}
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

void consumer() {

unique_lock<mutex> lock(mtx);

not_empty.wait(lock, [] { return in != out; });

int consume = buffer[out];

out = (out + 1) % bufsize;

not_full.notify_one();

lock.unlock();

cout << "The consumed value is " << consume << endl;

int main() {

int choice, produce;

while (true) {

cout << "1. Produce\t2. Consume\t3. Exit" << endl;

cout << "Enter your choice: ";

cin >> choice;

switch (choice) {

case 1:

cout << "Enter the value to produce: ";

cin >> produce;


Mirpur University of Science & Technology, MUST Mirpur
AJ&K

producer(produce);

break;

case 2:

consumer();

break;

case 3:

return 0;

default:

cout << "Invalid choice! Try again." << endl;

Output:

1. Produce 2. Consume 3. Exit

Enter your choice: 2

Buffer is Empty

1. Produce 2. Consume 3. Exit

Enter your choice: 1

Enter the value to produce: 100

1. Produce 2. Consume 3. Exit


Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Enter your choice: 2

The consumed value is 100

1. Produce 2. Consume 3. Exit

Enter your choice: 3

Outcomes:

 Students have learned what the producer-consumer problem is and how it can lead to
synchronization issues in multi-threaded programs.
 They have successfully implemented the producer-consumer problem using semaphores
in C++, ensuring proper synchronization between producer and consumer threads.
 Students will study the concepts of deadlock and starvation and their relevance in
concurrent systems.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

13
Implementation of File organization techniques-single level
directory and two-level directory

Objective:

The objective of this lab is to understand and implement two file organization techniques: Single
Level Directory and Two-Level Directory. These techniques are used to manage and organize
files in an operating system efficiently.

Single Level Directory: In Single Level Directory, all files are stored in a single directory. Each
file is uniquely identified by its name, and the directory maintains a mapping of filenames to
their respective locations in the storage.

Two-Level Directory: In Two-Level Directory, files are organized into two levels of directories:
a user-level directory and a file-level directory. Each user has a separate directory, and within
each user's directory, files are organized and accessed using their unique filenames.

Implementation.

Single Level Directory:

#include <iostream>

#include <string>

#include <vector>

using namespace std;

struct FileEntry {

string filename;

int startBlock;

int length;
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

};

class SingleLevelDirectory {

private:

vector<FileEntry> files;

int totalBlocks;

public:

SingleLevelDirectory(int blocks) : totalBlocks(blocks) {}

void addFile(string filename, int startBlock, int length) {

FileEntry entry;

entry.filename = filename;

entry.startBlock = startBlock;

entry.length = length;

files.push_back(entry);

void displayDirectory() {

cout << "Single Level Directory:" << endl;

cout << "-------------------------------" << endl;

cout << "Filename\tStart Block\tLength" << endl;

for (const auto& file : files) {

cout << file.filename << "\t\t" << file.startBlock << "\t\t" << file.length << endl;

cout << "-------------------------------" << endl;

}
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

};

int main() {

SingleLevelDirectory directory(100);

directory.addFile("file1.txt", 0, 5);

directory.addFile("file2.txt", 10, 8);

directory.addFile("file3.txt", 25, 12);

directory.displayDirectory();

return 0;

Two-Level Directory:
#include <iostream>

#include <string>

#include <vector>

using namespace std;

struct FileEntry {

string filename;

int startBlock;

int length;

};

struct UserEntry {

string username;

vector<FileEntry> files;
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

};

class TwoLevelDirectory {

private:

vector<UserEntry> users;

int totalBlocks;

public:

TwoLevelDirectory(int blocks) : totalBlocks(blocks) {}

void addUser(string username) {

UserEntry entry;

entry.username = username;

users.push_back(entry);

void addFile(string username, string filename, int startBlock, int length) {

for (auto& user : users) {

if (user.username == username) {

FileEntry file;

file.filename = filename;

file.startBlock = startBlock;

file.length = length;

user.files.push_back(file);

return;

}
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

void displayDirectory() {

cout << "Two-Level Directory:" << endl;

cout << "-------------------------------" << endl;

for (const auto& user : users) {

cout << "User: " << user.username << endl;

cout << "Filename\tStart Block\tLength" << endl;

for (const auto& file : user.files) {

cout << file.filename << "\t\t" << file.startBlock << "\t\t" << file.length << endl;

cout << "-------------------------------" << endl;

};

int main() {

TwoLevelDirectory directory(100);

directory.addUser("user1");

directory.addUser("user2");

directory.addFile("user1", "file1.txt", 0, 5);

directory.addFile("user2", "file2.txt", 10, 8);

directory.addFile("user1", "file3.txt", 25, 12);


Mirpur University of Science & Technology, MUST Mirpur
AJ&K

directory.displayDirectory();

return 0;

Students Task:

1. Implement an option in the Two-Level Directory program to delete a file given its filename and
the user who owns it.
2. Modify the Single Level Directory program to handle file deletions as well.

Outcomes:

By the end of this lab, students will be able to understand and implement the Single Level Directory and
Two-Level Directory file organization techniques. They will learn how these techniques manage and
organize files in an operating system. Additionally, students will gain hands-on experience in
programming and working with directories and files in C++.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

14
Implementation of Banker’s algorithm for deadlock avoidance

Objective:

The objective of this lab is to implement the Banker's algorithm in C++ to avoid deadlock
situations in a system with multiple processes and resources.

Deadlock is a situation in which two or more processes are unable to proceed because each is
waiting for the other to release a resource. Banker's algorithm is used for deadlock avoidance by
ensuring that the system is in a safe state before allocating resources to processes.

Implementation:

1. Include necessary libraries.


2. Define constants for the maximum number of processes (MAX_PROCESS) and resources
(MAX_RESOURCES).
3. Create a class named BankersAlgorithm with private data members to store information about
processes, resources, and availability.
4. Implement the constructor to initialize the class with the number of processes and resources.
5. Implement member functions to input the maximum resources, allocated resources, and calculate
the needed resources for each process.
6. Implement the Banker's algorithm to check for a safe state and allocate resources accordingly.

Source Code:

#include <iostream>

#include <vector>

using namespace std;

const int MAX_PROCESS = 10;

const int MAX_RESOURCES = 10;

class BankersAlgorithm {
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

private:

int numProcesses;

int numResources;

vector<vector<int>> maxResources;

vector<vector<int>> allocatedResources;

vector<vector<int>> neededResources;

vector<int> availableResources;

bool isSafeState(vector<bool>& visited) {

vector<int> work = availableResources;

vector<bool> safe(numProcesses, false);

int count = 0;

while (count < numProcesses) {

bool found = false;

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

if (!visited[i] && isSafe(i, work)) {

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

work[j] += allocatedResources[i][j];

safe[i] = true;

visited[i] = true;

found = true;

count++;

}
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

if (!found) {

break;

for (bool status : safe) {

if (!status) {

return false;

return true;

bool isSafe(int process, const vector<int>& work) {

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

if (neededResources[process][i] > work[i]) {

return false;

return true;

public:

BankersAlgorithm(int numP, int numR) : numProcesses(numP), numResources(numR) {

maxResources.resize(numProcesses, vector<int>(numResources));

allocatedResources.resize(numProcesses, vector<int>(numResources));
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

neededResources.resize(numProcesses, vector<int>(numResources));

availableResources.resize(numResources);

void inputMaxResources() {

cout << "Enter the maximum resources for each process:" << endl;

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

cout << "Process P" << i << ": ";

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

cin >> maxResources[i][j];

void inputAllocatedResources() {

cout << "Enter the allocated resources for each process:" << endl;

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

cout << "Process P" << i << ": ";

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

cin >> allocatedResources[i][j];

void calculateNeededResources() {

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


Mirpur University of Science & Technology, MUST Mirpur
AJ&K

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

neededResources[i][j] = maxResources[i][j] - allocatedResources[i][j];

void inputAvailableResources() {

cout << "Enter the available resources:" << endl;

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

cin >> availableResources[i];

bool isSafeState() {

vector<bool> visited(numProcesses, false);

return isSafeState(visited);

};

int main() {

int numProcesses, numResources;

cout << "Enter the number of processes: ";

cin >> numProcesses;

cout << "Enter the number of resources: ";

cin >> numResources;


Mirpur University of Science & Technology, MUST Mirpur
AJ&K

BankersAlgorithm banker(numProcesses, numResources);

banker.inputMaxResources();

banker.inputAllocatedResources();

banker.calculateNeededResources();

banker.inputAvailableResources();

if (banker.isSafeState()) {

cout << "The system is in a safe state. Resources can be allocated." << endl;

} else {

cout << "The system is in an unsafe state. Resources cannot be allocated without causing a
deadlock." << endl;

return 0;

Possible output can be:

Enter the number of processes: 5

Enter the number of resources: 3

Enter the maximum resources for each process:

Process P0: 7 5 3

Process P1: 3 2 2

Process P2: 9 0 2

Process P3: 2 2 2

Process P4: 4 3 3

Enter the allocated resources for each process:

Process P0: 0 1 0
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Process P1: 2 0 0

Process P2: 3 0 2

Process P3: 2 1 1

Process P4: 0 0 2

Enter the available resources:

332

The system is in a safe state. Resources can be allocated.

Student Task:

Modify the Banker's algorithm program to allow the user to dynamically add or remove
processes and resources. After inputting the initial number of processes and resources, provide
the user with options to add or remove processes/resources.
Outcomes:

1. Students will gain a clear understanding of the Banker's algorithm for deadlock avoidance.
2. They will learn how to implement the Banker's algorithm in C++ to determine if the system is in
a safe state.
3. Students will be able to identify whether resources can be safely allocated to processes without
causing deadlock.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

15
Implementation of deadlock detection algorithm

Objective:

The objective of this lab is to implement the deadlock detection algorithm in C++ to detect
whether a system is in a deadlock state or not. Deadlock detection is an essential part of
operating systems, as it allows the system to identify and resolve deadlock situations to ensure
proper resource management and system efficiency.

Deadlock is a situation in which two or more processes are unable to proceed because each is
waiting for the other to release a resource. Deadlock detection algorithms periodically check the
system's resource allocation state to determine if a deadlock has occurred.

Algorithm: The deadlock detection algorithm can be implemented using the following steps:

1. Initialize the necessary data structures to represent the system's resource allocation state,
such as the number of processes, the number of resources, and the allocation and request
matrices.
2. Implement a function to input the maximum resources, allocated resources, and resource
requests for each process.
3. Calculate the needed resources for each process by subtracting the allocated resources
from the maximum resources.
4. Implement a function to check if the system is in a deadlock state using the detection
algorithm:
a. Mark each process that has a row in the Allocation matrix of all zeros.
b. Initialize a temporary vector W to equal the Available vector.
c. Find an index i such that process i is currently unmarked and the i-th row of the
Request matrix is less than or equal to W. That is, Request[i][k] ≤ W[k], for 1 ≤ k
≤ m. If no such row is found, terminate the algorithm.
d. If such a row is found, mark process i and add the corresponding row of the
Allocation matrix to W. That is, set W[k] = W[k] + Allocation[i][k], for 1 ≤ k ≤
m. Return to step c.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

5. If all processes are marked, the system is in a deadlock state. Otherwise, it is in a safe
state.

Source Code

#include <iostream>

#include <vector>

using namespace std;

const int MAX_PROCESS = 10;

const int MAX_RESOURCES = 10;

class DeadlockDetectionAlgorithm {

private:

int numProcesses;

int numResources;

vector<vector<int>> allocationMatrix;

vector<vector<int>> requestMatrix;

public:

DeadlockDetectionAlgorithm(int numP, int numR) : numProcesses(numP), numResources(numR) {

allocationMatrix.resize(numProcesses, vector<int>(numResources));

requestMatrix.resize(numProcesses, vector<int>(numResources));

}
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

void inputAllocationMatrix() {

cout << "Enter the resource allocation matrix:" << endl;

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

cout << "Process P" << i << ": ";

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

cin >> allocationMatrix[i][j];

void inputRequestMatrix() {

cout << "Enter the resource request matrix:" << endl;

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

cout << "Process P" << i << ": ";

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

cin >> requestMatrix[i][j];

void detectDeadlock() {

vector<bool> deadlocked(numProcesses, false);


Mirpur University of Science & Technology, MUST Mirpur
AJ&K

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

if (!deadlocked[i]) {

bool canBeProcessed = true;

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

if (requestMatrix[i][j] > allocationMatrix[i][j]) {

canBeProcessed = false;

break;

if (!canBeProcessed) {

deadlocked[i] = true;

cout << "Deadlocked processes: ";

bool found = false;

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

if (deadlocked[i]) {

cout << "P" << i << " ";

found = true;

if (!found) {
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

cout << "None";

cout << endl;

};

int main() {

int numProcesses, numResources;

cout << "Enter the number of processes: ";

cin >> numProcesses;

cout << "Enter the number of resources: ";

cin >> numResources;

DeadlockDetectionAlgorithm detector (numProcesses, numResources);

detector.inputAllocationMatrix();

detector.inputRequestMatrix();

detector.detectDeadlock();

return 0;

Example output:

Enter the number of processes: 5

Enter the number of resources: 3


Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Enter the resource allocation matrix:

Process P0: 0 1 0

Process P1: 2 0 0

Process P2: 3 0 2

Process P3: 2 1 1

Process P4: 0 0 2

Enter the resource request matrix:

Process P0: 7 5 3

Process P1: 3 2 2

Process P2: 9 0 2

Process P3: 2 2 2

Process P4: 4 3 3

Deadlocked processes: P1 P2 P3 P4

Outcomes:

 Students will understand the deadlock detection algorithm and its significance in identifying
deadlock situations in a system.
 They will learn how to implement the deadlock detection algorithm in C++ to determine if
deadlock has occurred.
 Students will be able to identify and list the processes that are deadlocked in the system, if any,
after running the deadlock detection algorithm.

Student Task: Modify the given C++ program to implement the Banker's algorithm for deadlock
avoidance. Instead of detecting deadlock after resource allocation, implement the Banker's algorithm to
ensure safe resource allocation to processes. Use the provided class DeadlockDetectionAlgorithm and its
member functions to input the maximum resources, allocated resources, and needed resources for each
process. Then, implement the Banker's algorithm to check if the system is in a safe state and allocate
resources accordingly. Display the allocated resources for each process after successful allocation. Test
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

the program with different inputs to verify its correctness and effectiveness in avoiding deadlock
situations.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

16
Implementation of Least Recently Used (LRU) Page Replacement
Policy

Objective:

The objective of this lab is to implement the Least Recently Used (LRU) page replacement
policy in C++. The LRU page replacement algorithm replaces the least recently used page when
a new page needs to be loaded into memory.

Page Replacement Policies: In computer systems, the main memory (RAM) is used to store
data and instructions that are currently being used by a process. However, the available RAM is
limited, and it may not be able to hold all the data and instructions needed by various processes.
When a process requires more memory than is available, it may have to swap out some pages
from RAM to the disk and bring in new pages.

Page replacement policies are algorithms used by the operating system to decide which page to
remove from memory when a new page needs to be loaded. The goal of these policies is to
optimize memory usage and minimize page faults (instances where a process requests a page that
is not currently in RAM).

Least Recently Used (LRU) Page Replacement: The LRU page replacement policy works on
the principle that the least recently used page is the best candidate for replacement. The
algorithm keeps track of the order in which pages are used and removes the page that has not
been used for the longest time. This policy aims to reduce the number of page faults and improve
overall system performance.

Implementation:

1. Include necessary libraries.


2. Create a class named LRUPageReplacement with private data members to store the
number of frames, a list to maintain the order of page usage, and a hash map to keep track
of page positions in the list.
3. Implement the constructor to initialize the class with the number of frames.
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

4. Implement the referPage() function, which simulates the LRU page replacement policy. It
takes a vector of page references as input and iterates through each page.
5. For each page, check if it is already present in the page map.
6. If the page is not present, and the number of frames is already filled, remove the least
recently used page from the list and the map.
7. If the page is present, remove it from its current position in the list and update its position
to the front of the list.
8. Print the current page frames after each page reference.

Source Code:

#include <iostream>

#include <vector>
#include <unordered_map>
#include <list>
using namespace std;

class LRUPageReplacement {
private:
int numFrames;
list<int> pageList;
unordered_map<int, list<int>::iterator> pageMap;

public:
LRUPageReplacement(int frames) : numFrames(frames) {}

void referPage(vector<int>& pages) {


for (int page : pages) {
if (pageMap.find(page) == pageMap.end()) {
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

if (pageList.size() == numFrames) {
int lruPage = pageList.back();
pageList.pop_back();
pageMap.erase(lruPage);
}
} else {
pageList.erase(pageMap[page]);
}

pageList.push_front(page);
pageMap[page] = pageList.begin();
printPageFrames();
}
}
void printPageFrames() {
cout << "Current Page Frames: ";
for (int page : pageList) {
cout << page << " ";
}
cout << endl;
}
};

int main() {
int numFrames, numPages;
Mirpur University of Science & Technology, MUST Mirpur
AJ&K

cout << "Enter the number of frames: ";


cin >> numFrames;

cout << "Enter the number of pages: ";


cin >> numPages;
vector<int> pages(numPages);

cout << "Enter the page reference sequence: ";


for (int i = 0; i < numPages; i++) {
cin >> pages[i];
}
LRUPageReplacement lru(numFrames);
lru.referPage(pages);
return 0;
}
Possible Outcome:
Let's assume the number of frames is 3, and the number of pages is 6, and the page reference
sequence is {7, 0, 1, 2, 0, 3}.

Enter the number of frames: 3

Enter the number of pages: 6

Enter the page reference sequence: 7 0 1 2 0 3

Current Page Frames: 7

Current Page Frames: 0 7

Current Page Frames: 1 0 7


Mirpur University of Science & Technology, MUST Mirpur
AJ&K

Current Page Frames: 2 1 0

Current Page Frames: 2 1 0

Current Page Frames: 3 2 1

Outcomes:

 Students will understand the concept of page replacement policies and the importance of
efficient memory management in operating systems.
 They will learn about the Least Recently Used (LRU) page replacement policy and how it
works to minimize page faults.
 Students will gain hands-on experience in implementing the LRU page replacement
algorithm in C++ and simulating its behavior for a given page reference sequence.

Student Task: Modify the above implementation to support multiple page replacement policies
such as First-In-First-Out (FIFO) and Optimal Page Replacement and compare their performance
for different page reference sequences.

You might also like