Operating System Lab Manual

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 100

CS 313 – Operating System Lab Manual

ABASYN UNIVERSITY, ISLAMABAD CAMPUS

OPERATING SYSTEM CONCEPTS


CS 303

PREPARED BY

Ms Naveen Ahmed

REVIEWED & APPROVED BY

Mr. Abdul Hannan


(Head of Department)

DEPARTMENT OF COMPUTING
CS 313 – Operating System Lab Manual

LIST OF EXPERIMENTS/LABS
Lab No. 01: Introduction

Lab No. 02: Overview of Ubuntu

Lab No. 03: CPU Scheduling Algorithms

Lab No. 04: CPU Scheduling Algorithms

Lab No. 05: Multiprocessor Scheduling

Lab No. 06: Real Time Scheduling

Lab No. 07: Deadlock Management Techniques

Lab No. 08: Deadlock Management Techniques

Lab No. 09: Process Synchronization

Lab No. 10: Memory Management Techniques

Lab No. 11: Memory Management Techniques

Lab No. 12: Disk Management Algorithm

Lab No. 13: File Organization Techniques

Lab No. 14: File Allocation Strategies

Lab No. 15: Lab Exam


CS 313 – Operating System Lab Manual

LAB NO. 01
INTRODUCTION TO LINUX (UBUNTU) AND
COMMAND-LINE

Following are the lab objectives:

1. Understand the Linux Concept and Distributions


Lab 2. Understand the directory structure of Ubuntu

Objectives 3. Apply Linux Commands using Terminal

Roll No. Student Student Name


Obtained Marks
Marks Comments
Task 1 10
Task 2 10
Task 3 10
Task 4 10
Task 5 10
Total
50
Marks

Lab Instructor
CS 313 – Operating System Lab Manual

Lab Objectives and CLOs Mapping

Lab CLOs
Objectives a b c
1
2
3

Instructions
▪ This is individual Lab work/task.
▪ Complete this lab work within lab timing.
▪ Discussion with peers is not allowed.
▪ You can consult any book, notes & Internet.
▪ Copy paste from the Internet will give you negative marks.
▪ Lab work is divided into small tasks, completing all tasks sequentially.
▪ Show the solution of each lab task to your Lab Instructor.
▪ In-Lab Exercises/Tasks
▪ Write your code at provided space after each question
▪ You need to upload code for all tasks at LMS.
CS 313 – Operating System Lab Manual

INTRODUCTION TO LINUX (UBUNTU)


Linux
Linux is a generic term referring to Unix-like computer operating systems based on the Linux
kernel. Linux is actually just a kernel, so to create a complete Linux system you have to install
the source code of the kernel and many other freely distributed software programs.

The development of Linux is one of the most prominent examples of free and open source
software collaboration; typically all the underlying source code can be used, freely modified,
and redistributed by anyone.

Linux was developed by "Linus Torvalds" at the University of Helsinki, with the help of UNIX
programmers from across the Internet.

Linux Distributions
A typical Linux distribution comprises a Linux kernel, GNU tools and libraries, additional
software, documentation, a window system (the most common being the X Window System),
a window manager, and a desktop environment.

Most of the included software is free and open-source software made available both as compiled
binaries and in source code form, allowing modifications to the original software. Usually, Linux
distributions optionally include some proprietary software that may not be available in source
code form, such as binary blobs required for some device drivers.

Usually distributions are put on CD that contains the kernel and programming tools and utilities.
These distributions usually come with a setup program on CD to install a Linux system, they
have the same kernel but with different interfaces.

Some Linux based distributions are;

▪ Ubuntu
▪ RedHat
▪ Fedora
▪ Debian
▪ Slackware
▪ SUSE
CS 313 – Operating System Lab Manual

Figure 1: Linux Distributions

Directory Structure
File system: The way the files of an operating system are organized on the disk.
▪ All the files are grouped together in the directory structure. The file-system is arranged in
a hierarchical structure, like an inverted tree. The top of the hierarchy is traditionally
called root (written as a slash /).
▪ Linux sorts directories descending from the root directory according to their importance
to the boot process.
▪ File systems from other hard drive partitions mount to directories beneath the root
directory, providing access to a single directory structure.
▪ The File system hierarchy standard (FHS) governs the unified file system for Linux by
defining a standard set of directories, sub-directories and files.
▪ Linux is a case sensitive operating system.

Figure 2: Directory Structure of Linux (Ubuntu)


CS 313 – Operating System Lab Manual

Directory Description

The root directory, all directories are below the / (root directory)
/
of the system.

/bin Contains binary commands available to all users.

/boot Contains kernel and boot loader files.

/dev Contains device files.

/etc Contains system configuration files.

/home Contains by default the user home directories.

/lib Contains shared programs libraries and kernel modules.

/root Home directory for the root user.

/media Mount point for removable media.

/mnt Mount point for mounting a file system temporarily.

/opt Add-on application software packages.

/sbin Contains system binary commands.

/proc Contains information about system state and processes.

/srv Contains the files for services like FTP and Web servers.

/tmp Contains temporary files.

/usr Contains system commands and utilities.

/var Contains data files that are changed constantly.


CS 313 – Operating System Lab Manual

LINUX COMMANDS
1. pwd Command
The pwd command prints out the path of the current working directory (folder) you’re in. The
command will return an absolute (full) path, which is basically a path of all the directories that
starts with a forward slash (/).

Sample output of the command is shown.

2. cd Command
To navigate through the Linux files and directories, use the cd command. It requires either the
full path or the name of the directory, depending on the current working directory that you’re in.

Let’s say you’re in /home/username/Documents and you want to go to Photos, a subdirectory


of Documents. To do so, simply type the following command: cd Photos.

Another scenario is if you want to switch to a completely new directory, for example,
/home/username/Movies. In this case, you have to type cd followed by the directory’s absolute
path: cd /home/username/Movies.

There are some shortcuts to help you navigate quickly:

▪ cd .. (with two dots) to move one directory up


▪ cd to go straight to the home folder
▪ cd- (with a hyphen) to move to your previous directory
Sample output of the command is shown.

3. ls Command
The ls command is used to view the contents of a directory. By default, this command will
display the contents of the current working directory.

If we want to see the content of other directories, type ls and then the directory’s path. For
example, enter ls /home/username/Documents to view the content of Documents.
CS 313 – Operating System Lab Manual

There are variations we can use with the ls command:

● ls -R will list all the files in the sub-directories as well


● ls -a will show the hidden files
● ls -al will list the files and directories with detailed information like the permissions, size,
owner, etc.

Sample output of the command is shown.

4. mkdir Command
‘mkdir’ command creates a new directory in the current working directory.
Use mkdir command to make a new directory — if we type mkdir cs303 it will create a
directory called cs303.

There are extra mkdir commands as well:

● To generate a new directory inside another directory, use this Linux basic
command mkdir Music/Newfile
● use the p (parents) option to create a directory in between two existing directories. For
example, mkdir -p Music/2020/Newfile will create the new “2020” file.

Sample output of the command is shown.

5. rmdir Command
If we need to delete a directory, then we use the rmdir command. However, rmdir only allows
us to delete empty directories.
Sample output of the command is shown.

6. clear Command
‘clear’ command performs clear screen operation on the terminal.
Sample output of the command is shown.
CS 313 – Operating System Lab Manual

After running the clear command, screen on terminal is clear now.

7. cat Command
cat (short for concatenate) is one of the most frequently used commands in Linux. It is used to
list the contents of a file on the standard output (sdout). To run this command, type cat followed
by the file’s name and its extension. For instance: cat file.txt.

Here are other ways to use the cat command:

▪ cat > filename creates a new file


▪ cat filename1 filename2>filename3 joins two files (1 and 2) and stores the output of
them in a new file (3)
▪ to convert a file to upper or lower case use, cat filename | tr a-z A-Z >output.txt

Following are demonstrations of cat command to perform different tasks.

1) Writing Contents in Text File

We can write some text in a fresh file using cat command.

cat >info.txt

Some text of your choice.


CS 313 – Operating System Lab Manual

Press Ctrl + D

2) Display Contents of Text File

Display contents of an existing file.

cat info.txt

3) Concatenate Contents of Multiple Files

We can also concatenate the contents of multiple files into a single file
cat info.txt second.txt >third.txt

8. cp Command
The cp command is used to copy files from the current directory to a different directory.

For instance, the command cp scenery.jpg /home/username/Pictures would create a copy


of scenery.jpg (from your current directory) into the Pictures directory.
CS 313 – Operating System Lab Manual

9. mv Command
The primary use of the mv command is to move files, although it can also be used to rename
files.

The arguments in mv are similar to the cp command. We need to type mv, the file’s name, and
the destination’s directory. For example: mv file.txt /home/username/Documents.

To rename files, the Linux command is mv oldname.ext newname.ext

10. rm Command
The rm command is used to delete directories and the contents within them. If we only want to
delete the directory — as an alternative to rmdir — we use rm -r.

Note: Be very careful with this command and double-check which directory you are in. This will
delete everything and there is no undo.

11. sudo Command


Short for “SuperUser Do”, this command enables us to perform tasks that require administrative
or root permissions. However, it is not advisable to use this command for daily use because it
might be easy for an error to occur if we did something wrong.

12. whoami Command


whoami command is used both in Linux Operating System and as well as in Windows Operating
System.

▪ It is basically the concatenation of the strings “who”,”am”,”i” as whoami.


▪ It displays the username of the current user when this command is invoked.

13. man Command


man command in Linux is used to display the user manual of any command that we can run on
the terminal.

It provides a detailed view of the command which includes NAME, SYNOPSIS,


DESCRIPTION, OPTIONS, EXIT STATUS, RETURN VALUES, ERRORS, FILES,
VERSIONS, EXAMPLES, AUTHORS and SEE ALSO.

Every manual is divided into the following sections:


▪ Executable programs or shell commands
▪ System calls (functions provided by the kernel)
CS 313 – Operating System Lab Manual

▪ Library calls (functions within program libraries


▪ Games
▪ Special files (usually found in /dev)
▪ File formats and conventions eg /etc/passwd
▪ Miscellaneous (including macro packages and conventions), e.g. groff(7)
▪ System administration commands (usually only for root)
▪ Kernel routines [Non standard]

Syntax :
$man [OPTION]... [COMMAND NAME]...
Options and Examples

1. No Option: It displays the whole manual of the command.


Syntax :

$ man [COMMAND NAME]


Example:
$ man printf
Output:

In this example, manual pages of the command ‘printf‘ are simply returned.
CS 313 – Operating System Lab Manual

2. Section-num: Since a manual is divided into multiple sections so this option is used to display
only a specific section of a manual.

Syntax :
$ man [SECTION-NUM] [COMMAND NAME]
Example:
$ man 2 intro
Output:

In this example, the manual pages of command ‘intro‘ are returned which lies in the section 2.

3. -f option: One may not be able to remember the sections in which a command is present. So
this option gives the section in which the given command is present.

Syntax:
$ man -f [COMMAND NAME]
Example:
$ man -f ls
Output:
CS 313 – Operating System Lab Manual

In this example, the command ‘ls‘ is returned with its section number.

4. -a option: This option helps us to display all the available intro manual pages in succession.

Syntax:
$ man -a [COMMAND NAME]
Example:
$ man -a intro
Output:
CS 313 – Operating System Lab Manual

In this example you can move through the manual pages (sections) i.e. either reading (by
pressing Enter) or skipping (by pressing ctrl+D) or exiting (by pressing ctrl+C).
5. -k option: This option searches the given command as a regular expression in all the manuals
and it returns the manual pages with the section number in which it is found.

Syntax:
$ man -k [COMMAND NAME]
Example:
$ man -k cd
Output:

The command ‘cd‘ is searched in all the manual pages by considering it as a regular expression.

6. -w option: This option returns the location in which the manual page of a given command is
present.

Syntax:
$ man -w [COMMAND NAME]
Example:
$ man -w ls
Output:
CS 313 – Operating System Lab Manual

The location of command ‘ls‘ is returned.

7. -I option: It considers the command as case sensitive.

Syntax:
$ man -I [COMMAND NAME]
Example:
$ man -I printf
Output:
CS 313 – Operating System Lab Manual

The command ‘printf‘ is taken as case-sensitive i.e ‘printf‘ returns the manual pages but ‘Printf‘
gives error.

14. sort Command


Sort command is used to sort a file, arranging the records in a particular order. By default, the
sort command sorts file assuming the contents are ASCII. Using options in sort command, it can
also be used to sort numerically.
▪ SORT command sorts the contents of a text file, line by line.
▪ sort is a standard command line program that prints the lines of its input or concatenation
of all files listed in its argument list in sorted order.
▪ The sort command is a command line utility for sorting lines of text files. It supports
sorting alphabetically, in reverse order, by number, by month and can also remove
duplicates.
CS 313 – Operating System Lab Manual

▪ The sort command can also sort by items not at the beginning of the line, ignore case
sensitivity and return whether a file is sorted or not. Sorting is done based on one or more
sort keys extracted from each line of input.
▪ By default, the entire input is taken as a sort key. Blank space is the default field
separator.

The sort command follows these features as stated below:

1. Lines starting with a number will appear before lines starting with a letter.
2. Lines starting with a letter that appears earlier in the alphabet will appear before lines
starting with a letter that appears later in the alphabet.
3. Lines starting with a lowercase letter will appear before lines starting with the same letter
in uppercase.

Examples

Suppose you create a data file with name file.txt


Command:
$ cat > file.txt
asad
chaudary
saad
raja asim
naveen
danyal
haris

Sorting a file : Now use the sort command


Syntax :
$ sort filename.txt

Command:
$ sort file.txt
Output :
asad
chaudary
danyal
haris
CS 313 – Operating System Lab Manual

naveen
raja asim
saad

15. zip and unzip Commands


The zip command is used to compress files into a zip archive, and the unzip command is used to
extract the zipped files from a zip archive.
Sample output of the command is shown.

LAB TASKS
Task 1
Practice all the above Linux commands on your Ubuntu environment.

Task 2
What is the username which is logged-in?
What is the current working directory on your terminal?

Task 3
Perform following tasks.

▪ List the content of your home directory


▪ List the content of any directory by using its absolute path in first then its relative path
▪ List the content of any directory with the ls command and the option –R
▪ List the content of any directory with the ls command and the option -al or -a -l

Task 4
Perform following tasks.

▪ Create a directory CS303Lab1 using mkdir command


▪ Navigate into the directory CS303Lab1 using cd command
▪ Create a text file with the name of friends.txt, using cat command, having names of all
your friends.
CS 313 – Operating System Lab Manual

▪ Create another text file with the name of teachers.txt, using cat command, having names
of all your teachers.
▪ Print the contents of both files, i.e. friends.txt and teachers.txt, in sorting form.

Task 5
Perform following tasks.

▪ Duplicate the file friends.txt, having a different name, using cp command.


▪ Duplicate the file teachers.txt, having different names, using cp command.
▪ Now zip the all four files using zip command.

LAB NO. 02
EXECUTING C++ PROGRAM VIA SHELL
COMMANDS
Following are the lab objectives:
Lab
1. Installing C++ compiler in Ubuntu
Objectives 2. Executing C++ program using shell commands
CS 313 – Operating System Lab Manual

3. Executing C++ program using Makefile

Student
Roll No. Name
Obtained
Marks Comments
Marks
Task 1 10
Task 2 10
Task 3 20
Total
40
Marks

Lab Instructor

Lab Objectives and CLOs Mapping

Lab CLOs
Objectives a b c
1
2
3
CS 313 – Operating System Lab Manual

Instructions
▪ This is individual Lab work/task.
▪ Complete this lab work within lab timing.
▪ Discussion with peers is not allowed.
▪ You can consult any book, notes & Internet.
▪ Copy paste from the Internet will give you negative marks.
▪ Lab work is divided into small tasks, completing all tasks sequentially.
▪ Show the solution of each lab task to your Lab Instructor.
▪ In-Lab Exercises/Tasks
▪ Write your code at provided space after each question
▪ You need to upload code for all tasks at LMS.
CS 313 – Operating System Lab Manual

INSTALLING C++ COMPILER IN UBUNTU


Installing g++ Compiler
G++, the GNU C++ Compiler is a compiler in Linux which was developed to compile C++
programs. The file extensions that can be compiled with G++ are .c and .cpp. This will be
achieved by installing the build-essential package.

Although we can install the C++ compiler separately by installation of the gcc package, the
recommended way to install the C++ compiler on Ubuntu 20.04 is by installation of the entire
development package build-essential.

Syntax to install the package build-essential:

$ sudo apt install build-essential

Check C++ compiler version:

$ g++ --version

EXECUTE C++ PROGRAM VIA SHELL COMMANDS


Create a basic C++ code source using any editor in Ubuntu. For example we are going to use the
gedit command to open a cpp file in the built-in editor.

Step 1: Open a cpp file using gedit by running the following command at Terminal.

$ gedit helloworld.cpp

Step 2: Save the following code in helloworld.cpp text file.


#include <iostream>
using namespace std;

int main()
{
cout << "Hello, World!";
return 0;

}
CS 313 – Operating System Lab Manual

Step 3: Compile and execute the C++ code by running the following command at Terminal.

Note: Before running the following commands, make sure your working directory is the same
where the cpp code file is stored.

Following command is used to compile the source code.

$ g++ -c helloworld.cpp

Following command is used to make an executable file from cpp file.

$ g++ -o helloworld helloworld.cpp

Following command is used to run/execute the executable file.

$ ./helloworld

Table 1: Summary of G++ Compilation and Execution Commands


Command Description
This command is used to compile the C++
$ g++ -c helloworld.cpp code to check the syntax errors.
$ g++ -o helloworld This command is used to make an executable
helloworld.cpp file from C++ code.
This command is used to execute/run the
$ ./helloworld program using a generated executable file.

EXECUTE C++ PROGRAM USING MAKEFILE


Compiling the C++ source code files can be tedious, especially when we have to include several
source files and type the compiling command every time we need to compile. What is the
alternative? Makefiles are a simple way to organize code compilation procedure.
Makefiles are special format files that together with the make utility will help us to
automatically build and manage our projects (having multiple source files).
For example, let’s assume we have the following source files.
▪ main.cpp
▪ hello.cpp
CS 313 – Operating System Lab Manual

▪ factorial.cpp
▪ functions.h
Write the given C++ code in respective files using gedit editor.

main.cpp
The following is the code for main.cpp source file
#include <iostream>

#include "functions.h"

using namespace std;

int main(){
print_hello();
cout << endl;
cout << "The factorial of 5 is " << factorial(5) << endl;
return 0;
}

hello.cpp
The following is the code for hello.cpp source file
#include <iostream>

#include "functions.h"

using namespace std;

void print_hello(){
cout << "Hello World!";
}
CS 313 – Operating System Lab Manual

factorial.cpp
The following is the code for factorial.cpp source file.
#include "functions.h"

int factorial(int n){

if(n!=1){
return(n * factorial(n-1));
} else return 1;
}

functions.h
The following is the code for functions.h source file.
void print_hello();
int factorial(int n);

The trivial way to compile the files and obtain an executable, is by running the command

$ g++ main.cpp hello.cpp factorial.cpp –o hello

Warning: But we’ll NOT use this process of executable file generation.

Makefile
The make command allows us to manage large programs (with multiple files) or groups of
programs. As we begin to write large programs, we notice that re-compiling large programs takes
longer time than re-compiling short programs.
Create a Makefile listing the rules for building the executable, the file should be named
‘Makefile’ or ‘makefile’. This only has to be done once, except when new modules are added to
the program, the Makefile must be updated to add new module dependencies to existing rules
and to add new rules to build the new modules.
If we run :

$ make

This program will look for a file named Makefile in your directory, and then execute it.
CS 313 – Operating System Lab Manual

Makefile Composition
The basic Makefile is composed of:
target: dependencies
[tab] system command

First Makefile
Create a file with the name Makefile, and write following commands in the file.

all:
g++ main.cpp hello.cpp factorial.cpp –o output

In this first example we see that our target is called all. This is the default target for Makefiles.
The make utility will execute this target if no other one is specified.
We also see that there are no dependencies for target all, so make safely executes the system
commands specified.
Finally, make compiles the program according to the command line we gave it. Run following
commands at Terminal.

$ make
g++ main.cpp hello.cpp factorial.cpp –o output
$ ./output

Second Makefile
Create a second file with the name Makefile-2, and write following commands in the file.

all: make-2
make-2: main.o factorial.o hello.o
g++ main.o factorial.o hello.o –o output-2
main.o: main.cpp
g++ -c main.cpp
factorial.o: factorial.cpp
g++ -c factorial.cpp
hello.o: hello.cpp
CS 313 – Operating System Lab Manual

g++ -c hello.cpp
clean:
rm –rf *o output-2

Sometimes it is useful to use different targets. This is because if you modify a single file in your
project, you don't have to recompile everything, only what you modified.
In this example we see a target called clean. It is useful to have such target if you want to have
a fast way to get rid of all the object files and executables. Run the following commands at
Terminal.

$ make –f Makefile-2
g++ -c main.cpp
g++ -c factorial.cpp
g++ -c hello.cpp
g++ main.o factorial.o hello.o –o output-2
$ ./output-2

LAB TASKS
Task 1 (10 marks)
Write a C++ program which takes the width & length of Rectangle from the user. Display area
and perimeter of Rectangle. Use Makefile to execute your code via Terminal.

Task 2 (10 marks)


A software company sells a package that retails for $199. Quantity discounts are given according
to the following table.

Quantity Discount
1-50 No discount
Otherwise 20%
CS 313 – Operating System Lab Manual

Write a program that asks for the number of units purchased and computes the total cost of the
purchase. Use Makefile to execute your code via Terminal.

Task 3 (20 marks)

Create a class called Date that includes three pieces of information as data members; a month
(type int), a day (type int), and a year (type int). Your class should have three constructors that
initialize the three data members. For the purpose of this exercise, assume that the values
provided for the year and day are correct, but ensure that the month value is in the range 1-12; if
it isn’t, set the month to 1.

Provide setter and getter methods for each data member. Provide a member function
displayDate() that displays the month, day and year in the provided format, i.e. day – month –
year.

You need to create a header file, i.e. Date.h, which contains specification of class, creates
another file Data.cpp which contains all the implementations/definitions of methods available in
the class. Write a test program that demonstrates class Date’s capabilities. Use Makefile to
execute your code via Terminal.
CS 313 – Operating System Lab Manual

LAB NO. 03
SYSTEM CALLS
Following are the lab objectives:

1. Understand the concept of system calls


Lab 2. Understand the types of system calls

Objectives 3. Apply file manipulation system calls

4. Apply process control system calls

Roll No. Student Name


Obtained
Marks Comments
Marks
Task 1 10
Task 2 10
Task 3 10
Total
30
Marks

Lab Instructor
CS 313 – Operating System Lab Manual

Lab Objectives and CLOs Mapping

Lab CLOs
Objectives a b c
1
2
3

Instructions
▪ This is individual Lab work/task.
▪ Complete this lab work within lab timing.
▪ Discussion with peers is not allowed.
▪ You can consult any book, notes & Internet.
▪ Copy paste from the Internet will give you negative marks.
▪ Lab work is divided into small tasks, completing all tasks sequentially.
▪ Show the solution of each lab task to your Lab Instructor.
▪ In-Lab Exercises/Tasks
▪ Write your code at provided space after each question
▪ You need to upload code for all tasks at LMS.
CS 313 – Operating System Lab Manual

SYSTEM CALL
When a computer is turned on, the program that gets executed first is called the “operating
system”. It controls pretty much all the activities in the computer. This includes who logs-in,
how disks are used, how memory is used, how the CPU is used, and how you talk with other
computers. The operating system we use is called “Linux”.

The communication between the user program and the kernel is done by system calls. System
calls can be seen as special functions, called from the user program and performed by the kernel.
In simple words, “a request for the operating system to do something on behalf of the user’s
program”.

The system calls are the fundamental interface between an application and the Linux kernel. These calls
are generally available as functions written in C and C++, although certain low-level tasks (for
example, tasks where hardware must be accessed directly) may have to be written using
assembly-language instructions.

System calls are expensive. While a procedure call can usually be performed in a few machine
instructions. Whereas, a system call requires the computer to save its state, let the operating
system take control of the CPU, have the operating system perform some function, have the
operating system save its state, and then have the operating system give control of the CPU back
to you.

TYPES OF SYSTEM CALLS


System calls can be grouped roughly into six major categories:

1. File Manipulation/Management
2. Process Control
3. Device Management
4. Information Maintenance
5. Communications
6. Protection

File Manipulation System Calls


Following system calls for file management are available in the Linux;
▪ create file, delete file
▪ open, close
▪ read, write, reposition
▪ get file attributes, set file attributes
CS 313 – Operating System Lab Manual

Process Control System Calls


Following system calls for process control are available in the Linux;
▪ create process,
▪ terminate process
▪ load, execute
▪ get process attributes, set process attributes
▪ wait event, signal event
▪ allocate and free memory

Device Management System Calls


Following system calls for device management are available in the Linux;
▪ request device, release device
▪ read, write, reposition
▪ get device attributes, set device attributes
▪ logically attach or detach devices

Information Maintenance System Calls


Following system calls for information maintenance are available in the Linux;
▪ get time or date, set time or date
▪ get system data, set system data
▪ get process, file, or device attributes
▪ set process, file, or device attributes

Communications System Calls


Following system calls for communications are available in the Linux;
▪ create, delete communication connection
▪ send, receive messages
▪ transfer status information
▪ attach or detach remote devices

Protection System Calls


Following system calls for protection are available in the Linux;
▪ get file permissions
▪ set file permissions

FILE MANIPULATION SYSTEM CALLS IN C++


CS 313 – Operating System Lab Manual

The file structure related system calls available in the Linux system let us create, open, close,
read and write files, randomly access files, alias and remove files, get information about files,
check the accessibility of files, change protections, owner, and group of files, and control
devices. These operations either use a character string that defines the absolute or relative path
name of a file, or a small integer called a file descriptor that identifies the I/O channel.
Following file related system calls are being experimented in the lab:
▪ open()
▪ read()
▪ write()
▪ close()

File Descriptor
To the kernel, all open files are referred to by file descriptor. A file descriptor is a non-negative
integer. When we want to read or write a file, we identify the file with the file descriptor that is
returned by open as an argument to either read or write.
By convention, UNIX/Linux System shells associate file descriptor 0 with the standard input
of a process, file descriptor 1 with the standard output and file descriptor 2 with the standard
error.

open() System Call


open ( ) system call is used to know the file descriptor of user-created files. Since read and
write use file descriptor as their 1st parameter so to know the file descriptor open() system
call is used.
Syntax:
Prototype of the open function is given below.
#include <fcntl.h>
int open (const char * file_name, int oflag, ... /* mode_t mode
*/);

Here,

● file_name is the name to the file to open.


● oflag is used to define the file opening modes such as create, read, write modes.

Following are the possible options for oflag argument;

O_RDONLY Open for reading only.

O_WRONLY Open for writing only.


CS 313 – Operating System Lab Manual

O_RDWR Open for reading and writing.

O_APPEND Append to the end of file on each write.

Return value: Function returns the file descriptor.

Example:

fd = open (“file”, O_CREAT | O_RDWR, 0777);

read() System Call


read ( ) system call is used to read the content from the file. It can also be used to read the input
from the keyboard by specifying the 0 as file descriptor (see in the program given below).
Syntax:
#include <unistd.h>
length = read( file_descriptor, buffer, max_len);

Here,

● file_descriptor is the file descriptor of the file.


● buffer is the name of the buffer where data is to be stored.
● max_len is the number specifying the maximum amount of that data can be read

Return value: If successful read returns the number of bytes actually read.
Example:

n = read(0, buff, 50);

write() System Call


write ( ) system call is used to write the content to the file.
Syntax:
#include <unistd.h>
length = write( file_descriptor, buffer, len);

Here,
CS 313 – Operating System Lab Manual

● file_descriptor is the file descriptor of the file.


● buffer is the name of the buffer to be stored.
● len is the length of the data to be written.

Return value: If successful write() returns the number of bytes actually written.
Example:

n = write(fd, “Hello world!”, 12);

close() System Call


close() system call is used to close the opened file, it tells the operating system that you are done
with the file and close the file.
Syntax:
#include <unistd.h>
int close(int fd);

Here,

● fd is the file descriptor of the file to be closed.

Return value: If file closed successfully it returns 0, else it returns -1.


Example:

n = close(fd);

Complete Example
Following is the complete working example of the file manipulation system calls.

#include<unistd.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<iostream>

using namespace std;


CS 313 – Operating System Lab Manual

int main()
{
int n, fd;
char buff[50]; // declaring buffer

//message printing on the display


cout << "Enter text to write in the file:\n";

//read from keyboard, specifying 0 as fd for std input


device
//Here, n stores the number of characters
n= read(0, buff, 50);

// creating a new file using open.


fd=open("file.txt", O_CREAT | O_RDWR, 0777);

//writting input data to file (fd)


write(fd, buff, n);

//Write to display (1 is standard fd for output device)


write(1, buff, n);

//closing the file


close(fd);

return 0;
}
CS 313 – Operating System Lab Manual

PROCESS CONTROL SYSTEM CALLS IN C++


Concurrent programming is at the core of all professional applications. Multiple processes may
be designated to perform different tasks concurrently. Controlling multiple processes is a
challenging task and the operating system provides different system calls to handle this. The
process control provided by Linux includes the creation of new process, program execution, and
process termination.
Following process control related system calls are being experimented in the lab:
▪ fork()
▪ exit ()
▪ wait ()

Process Identifier
Every process has a unique process ID, a positive integer. The process ID is the only well-known
identifier of a process that is always unique. As processes terminate, their IDs become candidate
for reuse.

fork() System Call


fork ( ) system call is used to create a new process. This new process is called the child process.
This function is called once but returns twice. The only difference in the returns is that the return
value in the child is 0, whereas the return value in the parent is the process ID if the new child.
The reason the child’s process ID is returned to the parent is that a process can have more than
one child, and there is no function that allows a process to obtain the process IDs of its children.
The reason fork returns 0 to the child is that a process can have only a single parent, and the
child can always call getpid to obtain the process ID of its parent.
Both the child and the parent continue executing with the instruction that follows the call to
fork. The child is the copy of the parent.
Syntax:
Prototype of the fork function is given below.
#include <unistd.h>
pid_t fork (void);

There is no argument to the fork function.


Return value: Function returns;
▪ 0 in child
▪ Process ID of child in parent
▪ -1 on error
CS 313 – Operating System Lab Manual

Example 1:

#include <iostream>
#include <unistd.h>
using namespace std;
int main () {
fork();
cout << “hello world” << endl;
return 0;
}
See how many times the hello world will be printed.
Example 2:

#include <iostream>
#include <unistd.h>
using namespace std;

int main () {
fork();
fork();
cout << “hello world” << endl;
return 0;
}
See how many times the hello world will be printed.
Example 3:

#include <iostream>
#include <unistd.h>
using namespace std;

int main () {
int pid;
CS 313 – Operating System Lab Manual

pid = fork();

if( pid == -1 ){
cout << “Error in process generation” << endl;
}
else if( pid != 0 ){
cout << “This message is printed by child process” <<
endl;
}
else {
cout << “This message is printed by parent process” <<
endl;
}
return 0;
}
Observe the output of the program.

exit() System Call


exit( ) system call is used to terminate a process in normal condition.
Syntax:
Prototype of the exit function is given below.
#include <stdlib.h>
void exit (int status);

Here, status is the argument which we want to send to the OS for logging purposes.
Return value: Function doesn’t return any value.
Example:

#include <stdlib.h>

int main () {
exit(1); // process will exit here.
CS 313 – Operating System Lab Manual

return 0;
}
See how many times the hello world will be printed.

wait() System Call


When a process terminates, either normally or abnormally, the kernel notifies the parent by
sending the SIGCHLD signal to the parent. Because the termination of a child is an
asynchronous event – it can happen at any time which the parent is running. This signal is the
asynchronous notification from the kernel to the parent. The parent can choose to ignore this
signal, or it can handle the situation based on its choice.
wait () system call can block the parent until a child process to terminates.
Syntax:
#include <sys/wait.h>
Pid_t wait(int *statlock);

Here,

● statloc is expecting address of a static location where status will be stored.

Return value: function will return the process ID of the child process.
Example:

#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
using namespace std;

int main () {
int pid, pid2;
int status;

pid = fork();

if( pid == -1 ){
CS 313 – Operating System Lab Manual

cout << “Error in process generation” << endl;


}
else if( pid == 0 ){
exit(7);
}
cout << “Parent process is waiting for the child process”
<< endl;

pid2 = wait(&status);

if( pid2 == pid ) {


cout << “Child process has been terminated with status
= ”
<< status << endl;
}
return 0;
}

LAB TASKS
Task 1 (10 marks)
Write a C++ program which takes file name from user and creates the file using file
management system call. Later on, ask the user to enter the data which he/she wants to store in
the file and save the file with provided contents. Demonstrate your program using Makefile
utility.

Task 2 (10 marks)


Write a C++ program which takes names of two files, i.e. file_name_1 and file_name_2. Copy
the contents of the first file into the second file. Demonstrate your program using Makefile
utility.
CS 313 – Operating System Lab Manual

Task 3 (10 marks)

Write a C++ program which calls fork function 2 times in main function. Print process ID of
each child process using getpid function. Explore the manual of getpid function and use it.

LAB NO. 04
CPU SCHEDULING
Following are the lab objectives:

1. Implement First Come First Serve (FCFS) Algorithm

Lab 2. Implement Shortest Job First (SJF) Algorithm


Objectives 3. Implement Shortest Remaining Time First (SRTF)

Algorithm

Roll No. Student Name


Obtained
Marks Comments
Marks
Task 1 20
Task 2 20
Total
40
Marks

Lab Instructor
CS 313 – Operating System Lab Manual
CS 313 – Operating System Lab Manual

Lab Objectives and CLOs Mapping

Lab CLOs
Objectives a b c
1
2
3

Instructions
▪ This is individual Lab work/task.
▪ Complete this lab work within lab timing.
▪ Discussion with peers is not allowed.
▪ You can consult any book, notes & Internet.
▪ Copy paste from the Internet will give you negative marks.
▪ Lab work is divided into small tasks, completing all tasks sequentially.
▪ Show the solution of each lab task to your Lab Instructor.
▪ In-Lab Exercises/Tasks
▪ Write your code at provided space after each question
▪ You need to upload code for all tasks at LMS.
CS 313 – Operating System Lab Manual

CPU SCHEDULING
CPU scheduling is the basis of multiprogrammed operating systems. By switching the CPU
among processes, the operating system can make the computer more productive. CPU scheduling
deals with the problem of deciding which of the processes in the ready queue is to be allocated to
the CPU. There are many different CPU-scheduling algorithms, like;

1. First Come First Serve (FCFS)


2. Shortest Job First (SJF)
3. Shortest Remaining Time First (SRTF)
4. Priority Scheduling
5. Round Robin
6. Multilevel Queue
7. Multilevel Feedback Queue

For better simulation of above mentioned algorithms we need to have two prerequisites;

a. Struct to Represent Process


b. Queue to represent Ready Queue

Struct to Represent Process


A process can be represented by a struct which contains basic information related to process,
like, process ID, arrival time, burst time, wait time, turnaround time, etc. Following is the sample
structure. You can add more information if you require.

struct process
{
int pid;
int arrivalTime;
int burstTime;
int waitTime;
int turnaroundTime;
};
CS 313 – Operating System Lab Manual

Queue to Represent Ready Queue


Ready queue is the place where all processes reside and wait for their turn to acquire the CPU.
For this purpose we need to implement a queue data structure of type process. You can
implement your own class of queue (implemented in data structures course) or a built-in ADT of
Standard Template Library (STL). Please explore the STL queue with the following resources.
● http://www.cplusplus.com/reference/queue/queue/
● https://www.geeksforgeeks.org/queue-cpp-stl/

LAB TASKS
Task 1 (20 marks)
Write C++ program to simulate the First Come First Serve (FCFS) algorithm to manage
processes. For process representation struct process must be used. All processes should
be stored to the ready queue with proper information (burst time, arrival time, etc.). Later on
display the process ID, burst time, wait time, turnaround time, average wait time and
average turnaround time.

An abstract algorithm is given below;

1- Input the processes along with their burst time (bt).

2- Find waiting time (wt) for all processes.

3- As first process that comes need not to wait so

waiting time for process 1 will be 0 i.e. wt[first process]


= 0.

4- Find waiting time for all other processes i.e. for process i
->

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

5- Find turnaround time = waiting_time + burst_time

for all processes.

6- Find average waiting time =

total_waiting_time / no_of_processes.
CS 313 – Operating System Lab Manual

7- Similarly, find average turnaround time =

total_turn_around_time / no_of_processes.

Task 2 (20 marks)


Write C++ program to simulate the Shortest Job First (SJF) algorithm to manage processes. For
process representation struct process must be used. All processes should be stored to the
ready queue with proper information (burst time, arrival time, etc.). Later on display the process
ID, burst time, wait time, turnaround time, average wait time and average turnaround
time.

An abstract algorithm is given below;

1. Sort all the processes according to the arrival time.


2. Then select that process which has minimum arrival time and
minimum Burst time.
3. After completion of process make a pool of processes which
after till the completion of previous process and select that
process among the pool which is having minimum Burst time.

EXTRA TASKS
Task

Write C++ program to simulate Shortest Remaining Time First (SRTF) algorithm to manage
processes. For process representation struct process must be used. All processes should
be stored to the ready queue with proper information (burst time, arrival time, etc.). Later on
display the process ID, burst time, wait time, turnaround time, average wait time and
average turnaround time.
CS 313 – Operating System Lab Manual

LAB NO. 05
CPU SCHEDULING (PREEMPTIVE
ALGORITHMS)
Following are the lab objectives:

1. Implement Priority Scheduling Algorithm


Lab 2. Implement Highest Response Ratio Next (HRRN)
Objectives
Algorithm

Roll No. Student Name


Obtained
Marks Comments
Marks
Task 1 20
Task 2 20
Total
40
Marks

Lab Instructor
CS 313 – Operating System Lab Manual

Lab Objectives and CLOs Mapping

Lab CLOs
Objectives a b c
1
2
3

Instructions
▪ This is individual Lab work/task.
▪ Complete this lab work within lab timing.
▪ Discussion with peers is not allowed.
▪ You can consult any book, notes & Internet.
▪ Copy paste from the Internet will give you negative marks.
▪ Lab work is divided into small tasks, completing all tasks sequentially.
▪ Show the solution of each lab task to your Lab Instructor.
▪ In-Lab Exercises/Tasks
▪ Write your code at provided space after each question
▪ You need to upload code for all tasks at LMS.
CS 313 – Operating System Lab Manual

CPU SCHEDULING
CPU scheduling is the basis of multiprogrammed operating systems. By switching the CPU
among processes, the operating system can make the computer more productive. CPU scheduling
deals with the problem of deciding which of the processes in the ready queue is to be allocated to
the CPU. There are many different CPU-scheduling algorithms, like;

1. First Come First Serve (FCFS)


2. Shortest Job First (SJF)
3. Shortest Remaining Time First (SRTF)
4. Priority Scheduling
5. Round Robin
6. Highest Response Ratio Next (HRRN)
7. Multilevel Queue
8. Multilevel Feedback Queue

For better simulation of above mentioned algorithms we need to have two prerequisites;

a. Struct to Represent Process


b. Queue to represent Ready Queue

Struct to Represent Process


A process can be represented by a struct which contains basic information related to process,
like, process ID, arrival time, burst time, wait time, turnaround time, etc. Following is the sample
structure. You can add more information if you require.

struct process_control_block
{
int pid;
int status;
int arrivalTime;
int burstTime;
int waitTime;
int turnaroundTime;
};
CS 313 – Operating System Lab Manual

Queue to Represent Ready Queue


Ready queue is the place where all processes reside and wait for their turn to acquire the CPU.
For this purpose we need to implement a queue data structure of type process. You can
implement your own class of queue (implemented in data structures course) or a built-in ADT of
Standard Template Library (STL). Please explore the STL queue with the following resources.
● http://www.cplusplus.com/reference/queue/queue/
● https://www.geeksforgeeks.org/queue-cpp-stl/

LAB TASKS
Task 1 (20 marks)
Write C++ program to simulate Priority Scheduling algorithm to manage processes. For process
representation struct process must be used. All processes should be stored to the ready
queue with proper information (burst time, arrival time, etc.). Later on display the process ID,
burst time, wait time, turnaround time, average wait time and average turnaround time.

(Paste your code here)

EXTRA TASK: (20 marks)


Write C++ program to simulate the Highest Response Ratio Next (HRRN) algorithm to manage
processes. For process representation struct process must be used. All processes should
be stored to the ready queue with proper information (burst time, arrival time, etc.). Later on
display the process ID, burst time, wait time, turnaround time, average wait time and
average turnaround time.

(Paste your code here)


CS 313 – Operating System Lab Manual

LAB NO. 06
REAL-TIME SCHEDULING
Following are the lab objectives:

1. Implement Earliest-Deadline-First Scheduling Algorithm


Lab 2. Implement Monotonic Algorithm
Objectives

Roll No. Student Name


Obtained
Marks Comments
Marks
Task 1 20
Task 2 20
Total
40
Marks

Lab Instructor
CS 313 – Operating System Lab Manual

Lab Objectives and CLOs Mapping

Lab CLOs
Objectives 1 2 3 4 5
1
2

Instructions
▪ This is individual Lab work/task.
▪ Complete this lab work within lab timing.
▪ Discussion with peers is not allowed.
▪ You can consult any book, notes & Internet.
▪ Copy paste from the Internet will give you negative marks.
▪ Lab work is divided into small tasks, completing all tasks sequentially.
▪ Show the solution of each lab task to your Lab Instructor.
▪ In-Lab Exercises/Tasks
▪ Write your code at provided space after each question
▪ You need to upload code for all tasks at LMS
.
CS 313 – Operating System Lab Manual

REAL-TIME SCHEDULING
Real-time systems are systems that carry real-time tasks. These tasks need to be performed
immediately with a certain degree of urgency. A hard real-time task must be performed at a
specified time which could otherwise lead to huge losses. In soft real-time tasks, a specified
deadline can be missed. This is because the task can be rescheduled (or) can be completed after
the specified time,

In real-time systems, the scheduler is considered as the most important component which is
typically a short-term task scheduler. The main focus of this scheduler is to reduce the response
time associated with each of the associated processes instead of handling the deadline.

If a preemptive scheduler is used, the real-time task needs to wait until its corresponding tasks
time slice completes. In the case of a non-preemptive scheduler, even if the highest priority is
allocated to the task, it needs to wait until the completion of the current task. This task can be
slow (or) of the lower priority and can lead to a longer wait.

A better approach is designed by combining both preemptive and non-preemptive scheduling.


This can be done by introducing time-based interrupts in priority based systems which means the
currently running process is interrupted on a time-based interval and if a higher priority process
is present in a ready queue, it is executed by preempting the current process.

Struct to Represent Process


A process can be represented by a struct which contains basic information related to process,
like, process ID, arrival time, burst time, wait time, turnaround time, etc. Following is the sample
structure. You can add more information if you require.

struct real_time_process
{
int pid;
int status;
int readyTime;
int startingTime;
int completionTime;
int processingTime;
int priority;
};
CS 313 – Operating System Lab Manual

Queue to Represent Ready Queue


Ready queue is the place where all processes reside and wait for their turn to acquire the CPU.
For this purpose we need to implement a queue data structure of type real_time_process.
You can implement your own class of queue (implemented in data structures course) or a built-in
ADT of Standard Template Library (STL). Please explore the STL queue with the following
resources.
● http://www.cplusplus.com/reference/queue/queue/
● https://www.geeksforgeeks.org/queue-cpp-stl/

LAB TASKS
Task (30 marks)
Write C++ program to simulate Earliest Deadline First Scheduling algorithm to manage real-
time periodic processes. For process representation struct real_time_process must be
used. All processes should be stored to the ready queue with proper information (burst time,
arrival time, etc.). Later on display the process ID, ready time, starting time, completion time,
processing time and priority.

(Paste your code here)

EXTRA TASK
Task
Write C++ program to simulate Monotonic algorithms to manage real-time processes. For
process representation struct real_time_process must be used. All processes should
be stored to the ready queue with proper information (burst time, arrival time, etc.). Later on
display the process ID, ready time, starting time, completion time, processing time and
priority.

(Paste your code here)


CS 313 – Operating System Lab Manual

LAB NO. 07
DEADLOCK PREVENTION OR AVOIDANCE
TECHNIQUE
Following are the lab objectives:

1. Implement Banker’s Algorithm.


Lab
Objectives

Roll No. Student Name


Obtained
Marks Comments
Marks
Task 30
Total
30
Marks

Lab Instructor
CS 313 – Operating System Lab Manual

Lab Objectives and CLOs Mapping

Lab CLOs
Objectives 1 2 3 4 5
1
2

Instructions
▪ This is individual Lab work/task.
▪ Complete this lab work within lab timing.
▪ Discussion with peers is not allowed.
▪ You can consult any book, notes & Internet.
▪ Copy paste from the Internet will give you negative marks.
▪ Lab work is divided into small tasks, completing all tasks sequentially.
▪ Show the solution of each lab task to your Lab Instructor.
▪ In-Lab Exercises/Tasks
▪ Write your code at provided space after each question
▪ You need to upload code for all tasks at LMS.
CS 313 – Operating System Lab Manual

DEADLOCK PREVENTION OR AVOIDANCE


The banker’s algorithm is a resource allocation and deadlock avoidance algorithm that
tests for safety by simulating the allocation for predetermined maximum possible
amounts of all resources, then makes an “s-state” check to test for possible activities,
before deciding whether allocation should be allowed to continue.
Safety Algorithm: The algorithm for finding out whether or not a system is in a safe
state can be described as follows:

1) Let Work and Finish be vectors of length ‘m’ and ‘n’ respectively.

Initialize: Work = Available

Finish[i] = false; for i=1, 2, 3, 4….n

2) Find an i such that both

a) Finish[i] = false

b) Needi <= Work

if no such i exists goto step (4)

3) Work = Work + Allocation[i]

Finish[i] = true
CS 313 – Operating System Lab Manual

goto step (2)

4) if Finish [i] = true for all i

then the system is in a safe state

Resource-Request Algorithm: Let Requesti be the request array for process Pi. Requesti
[j] = k means process Pi wants k instances of resource type Rj. When a request for
resources is made by process Pi, the following actions are taken:

1) If Requesti <= Needi

Goto step (2) ; otherwise, raise an error condition, since the process has exceeded its
maximum claim.

2) If Requesti <= Available

Goto step (3); otherwise, Pi must wait, since the resources are not available.

3) Have the system pretend to have allocated the requested resources to process Pi by
modifying the state as follows:

Available = Available – Requesti

Allocationi = Allocationi + Requesti

Needi = Needi– Requesti


CS 313 – Operating System Lab Manual

LAB TASKS
Task 01 (15 marks)
Write C++ program to simulate Banker’s Algorithms for Deadlock avoidance.

(Paste your code here)

Extra Task (15 marks)


Write a C++ program to simulate a single processor system has three resource types X, Y and Z,
which are shared by three processes. There are 5 units of each resource type. Consider the
following scenario, where the column alloc denotes the number of units of each resource type
allocated to each process, and the column request denotes the number of units of each resource
type requested by a process in order to complete execution. Which of these processes will finish
LAST?

Alloc Request

X Y Z X Y Z

P0 1 2 1 1 0 3

P1 2 0 1 0 1 2

P2 2 2 1 1 2 0

(Paste your code here)


CS 313 – Operating System Lab Manual

LAB NO. 08
PROCESS SYNCHRONIZATION
CRITICAL SECTION PROBLEM
Following are the lab objectives:

1. Simulate Peterson’s Solution for the critical section


Lab Problem.
Objectives 2. Simulate process synchronization and Implement
Bounded-Buffer Problem.

Roll No. Student Name


Obtained
Marks Comments
Marks
Task 30
Total
30
Marks

Lab Instructor
CS 313 – Operating System Lab Manual

Lab Objectives and CLOs Mapping

Lab CLOs
Objectives a b c
1
2
3

Instructions
▪ This is individual Lab work/task.
▪ Complete this lab work within lab timing.
▪ Discussion with peers is not allowed.
▪ You can consult any book, notes & Internet.
▪ Copy paste from the Internet will give you negative marks.
▪ Lab work is divided into small tasks, completing all tasks sequentially.
▪ Show the solution of each lab task to your Lab Instructor.
▪ In-Lab Exercises/Tasks
▪ Write your code at provided space after each question
▪ You need to upload code for all tasks at LMS.
CS 313 – Operating System Lab Manual

Critical Section Problem


Critical section is a code segment that can be accessed by only one process at a time.

In the entry section, the process requests for entry in the Critical Section.
A simple solution to the critical section can be thought as shown below,
acquireLock();
Process Critical Section
releaseLock();

Peterson’s Solution
Peterson’s Solution is a classical software based solution to the critical section problem.
In Peterson’s solution, we have two shared variables:
● boolean flag[i] :Initialized to FALSE, initially no one is interested in entering
the critical section
● int turn : The process whose turn is to enter the critical section.
CS 313 – Operating System Lab Manual

PROCESS SYNCHRONIZATION
We use semaphores for synchronization, since that is the traditional way to present
such solutions.

Bounded-buffer (or Producer-Consumer) Problem:


Bounded Buffer problem is also called producer consumer problem..A semaphore
S is an integer variable that can be accessed only through two standard operations :
wait() and signal().The wait() operation reduces the value of semaphore by 1 and
the signal() operation increases its value by 1.

wait(S){

while(S<=0); // busy waiting

S--;
CS 313 – Operating System Lab Manual

signal(S){

S++;

LAB TASKS
Task 01: (15 marks)
Write a C++ program to simulate Peterson’s solution for the critical section problem.

(Paste your code here)

EXTRA TASK: (15 marks)

Write C++ program to simulate a Bounded-Buffer problem for process synchronization.

(Paste your code here)


CS 313 – Operating System Lab Manual

LAB NO. 09
PROCESS SYNCHRONIZATION
MUTUAL EXCLUSION ALGORITHM
SEMAPHORE
Following are the lab objectives:

Lab 1. Implement Readers-Writers Problem


Objectives 2. Implement Dining-Philosophers Problem

Roll No. Student Name


Obtained
Marks Comments
Marks
Task 1 15
Task 2 15
Total
30
Marks

Lab Instructor
CS 313 – Operating System Lab Manual

Lab Objectives and CLOs Mapping

Lab CLOs
Objectives a b c
1
2
3

Instructions
▪ This is individual Lab work/task.
▪ Complete this lab work within lab timing.
▪ Discussion with peers is not allowed.
▪ You can consult any book, notes & Internet.
▪ Copy paste from the Internet will give you negative marks.
▪ Lab work is divided into small tasks, completing all tasks sequentially.
▪ Show the solution of each lab task to your Lab Instructor.
▪ In-Lab Exercises/Tasks
▪ Write your code at provided space after each question
▪ You need to upload code for all tasks at LMS.
CS 313 – Operating System Lab Manual

1. Dining-Philosophers Problem:
The Dining Philosopher Problem states that K philosophers are seated around a
circular table with one chopstick between each pair of philosophers. There is one
chopstick between each philosopher.
process P[i]

while true do

THINK;

PICKUP(CHOPSTICK[i], CHOPSTICK[i+1 mod 5]);

EAT;

PUTDOWN(CHOPSTICK[i], CHOPSTICK[i+1 mod 5])

2. Readers and Writers Problem:


Suppose that a database is to be shared among several concurrent processes. Some
of these processes may want only to read the database, whereas others may want to
update (that is, to read and write) the database.
CS 313 – Operating System Lab Manual

do {

// Reader wants to enter the critical section

wait(mutex);

// The number of readers has now increased by 1

readcnt++;

// there is atleast one reader in the critical section

// this ensure no writer can enter if there is even one reader

// thus we give preference to readers here

if (readcnt==1)

wait(wrt);

// other readers can enter while this current reader is inside


CS 313 – Operating System Lab Manual

// the critical section

signal(mutex);

// current reader performs reading here

wait(mutex); // a reader wants to leave

readcnt--;

// that is, no reader is left in the critical section,

if (readcnt == 0)

signal(wrt); // writers can enter

signal(mutex); // reader leaves

} while(true);
CS 313 – Operating System Lab Manual

LAB TASKS

Task 1: (15 marks)


Write C++ program to simulate Readers-Writers problem for process synchronization.

(Paste your code here)

Extra Task: (15


marks)
Write C++ program to simulate Dining-Philosophers problem for process synchronization.

(Paste your code here)


CS 313 – Operating System Lab Manual

LAB NO. 10
MEMORY MANAGEMENT TECHNIQUES
Following are the lab objectives:
1. To simulate the MFT memory management
techniques.
Lab 2. To simulate the MVT memory management
Objectives techniques.

Roll No. Student Name


Obtained
Marks Comments
Marks
Task 1 15
Task 2 15
Total
30
Marks

Lab Instructor
CS 313 – Operating System Lab Manual

Lab Objectives and CLOs Mapping

Lab CLOs
Objectives a b c
1
2
3

Instructions
▪ This is individual Lab work/task.
▪ Complete this lab work within lab timing.
▪ Discussion with peers is not allowed.
▪ You can consult any book, notes & Internet.
▪ Copy paste from the Internet will give you negative marks.
▪ Lab work is divided into small tasks, completing all tasks sequentially.
▪ Show the solution of each lab task to your Lab Instructor.
▪ In-Lab Exercises/Tasks
▪ Write your code at provided space after each question
▪ You need to upload code for all tasks at LMS.

Memory management keeps track of the status of each memory location, whether it is
allocated or free.
MFT (Multiprogramming with a Fixed number of Tasks):
CS 313 – Operating System Lab Manual

MFT (Multiprogramming with a Fixed number of Tasks) is one of the old memory
management techniques in which the memory is partitioned into fixed size partitions and
each job is assigned to a partition.

if(pn[i]==pn[j])

f=1;

if(f==0){

if(ps[i]<=siz)

extft=extft+size-ps[i];

avail[i]=1;

count++;

MVT (Multiprogramming with a Variable number of Tasks):


MVT (Multiprogramming with a Variable number of Tasks) is the memory management
technique in which each job gets just the amount of memory it needs.
CS 313 – Operating System Lab Manual

if(pn[i]==pn[j])

f=1;

if(f==0)

if(ps[i]<=size )

extft=extft+size-ps[i];

avail[i]=1;

count++;

LAB TASKS
CS 313 – Operating System Lab Manual

Task 01 : (15 marks)


Write C++ program to simulate MVT memory management scheme with unequal sized
partitions.

(Paste your code here)

Task 02: (15 marks)


Write C++ program to simulate MFT memory management scheme with unequal sized
partitions.

(Paste your code here)


CS 313 – Operating System Lab Manual

LAB NO. 11
MEMORY MANAGEMENT TECHNIQUES
Following are the lab objectives:
1. To simulate the First Fit contiguous memory allocation
techniques.
2. To simulate the Best Fit contiguous memory allocation
Lab
techniques.
Objectives
3. To simulate the Worst Fit contiguous memory allocation
techniques

Roll No. Student Name


Obtained
Marks Comments
Marks
Task 1 15
Task 2 15
Total
30
Marks

Lab Instructor
CS 313 – Operating System Lab Manual

Lab Objectives and CLOs Mapping

Lab CLOs
Objectives a b c
1
2
3

Instructions
▪ This is individual Lab work/task.
▪ Complete this lab work within lab timing.
▪ Discussion with peers is not allowed.
▪ You can consult any book, notes & Internet.
▪ Copy paste from the Internet will give you negative marks.
▪ Lab work is divided into small tasks, completing all tasks sequentially.
▪ Show the solution of each lab task to your Lab Instructor.
▪ In-Lab Exercises/Tasks
▪ Write your code at provided space after each question
▪ You need to upload code for all tasks at LMS.
CS 313 – Operating System Lab Manual

There are different Placement Algorithm:


A. First Fit
B. Best Fit
C. Worst Fit
D. Next Fit
1. First Fit: In the first fit, the partition is allocated which is the first sufficient block
from the top of Main Memory..

Implementation
1.Input memory blocks with size and processes with size.
2.Initialize all memory blocks as free.
3.Start by picking each process and check if it can
be assigned to the current block.
4.If size-of-process <= size-of-block if yes then
assign and check for the next process.
5.If not then keep checking the further blocks.
2. Best Fit Allocates the process to the partition which is the first smallest sufficient
partition among the free available partitions.
CS 313 – Operating System Lab Manual

Implementation:
1.Input memory blocks and processes with sizes.
2. Initialize all memory blocks as free.
3.Start by picking each process and find the
minimum block size that can be assigned to
current process i.e., find min(bockSize[1],
blockSize[2],.....blockSize[n]) >
processSize[current], if found then assign
to the current process.
4. If not then leave that process and keep checking
the further processes.
3.Worst Fit: Allocates the process to the partition which is the largest sufficient
among the freely available partitions available in the main memory..
CS 313 – Operating System Lab Manual

Implementation:
1- Input memory blocks and processes with sizes.
2- Initialize all memory blocks as free.
3- Start by picking each process and find the
maximum block size that can be assigned to
current process i.e., find max(bockSize[1],
blockSize[2],.....blockSize[n]) >
processSize[current], if found then assign
to the current process.
5- If not then leave that process and keep checking
the further processes.

4. Next Fit: Next fit is similar to the first fit but it will search for the first sufficient
partition from the last allocation point.
CS 313 – Operating System Lab Manual

LAB TASKS
Task 1 (15 marks)
Write C++ program to simulate First Fit contiguous memory allocation techniques

(Paste your code here)

Task 2 (15 marks)


Write C++ program to simulate Best Fit contiguous memory allocation techniques

(Paste your code here)

Extra Task (15 marks)


Write C++ program to simulate Worst Fit contiguous memory allocation techniques

(Paste your code here)


CS 313 – Operating System Lab Manual

LAB NO. 12
Segmentation MEMORY MANAGEMENT
TECHNIQUES
Following are the lab objectives:
1. To simulate two-level paging technique of memory
management.
Lab 2. To simulate segmentation memory management technique.
Objectives

Roll No. Student Name


Obtained
Marks Comments
Marks
Task 1 15
Task 2 15
Total
30
Marks

Lab Instructor
CS 313 – Operating System Lab Manual

Lab Objectives and CLOs Mapping

Lab CLOs
Objectives a b c
1
2
3

Instructions
▪ This is individual Lab work/task.
▪ Complete this lab work within lab timing.
▪ Discussion with peers is not allowed.
▪ You can consult any book, notes & Internet.
▪ Copy paste from the Internet will give you negative marks.
▪ Lab work is divided into small tasks, completing all tasks sequentially.
▪ Show the solution of each lab task to your Lab Instructor.
▪ In-Lab Exercises/Tasks
▪ Write your code at provided space after each question
▪ You need to upload code for all tasks at LMS.
CS 313 – Operating System Lab Manual

PAGING AND TWO LEVEL-PAGING TECHNIQUE:


In computer operating systems, paging is one of the memory management schemes by
which a computer stores and retrieves data from the secondary storage for use in main
memory.When a process is to be executed, its pages are loaded into any available
memory frames from their source.Now if the size of inner page Table is Less Than or
Equal to size of a Frame then we can stop here as we are able to keep the outermost table
in a Single frame. This is called Two Level Paging.

Example:
Physical Address Space = 2(44) B

Virtual Address Space = 2(32) B

Page Entry = 4B

Page Size = 4Kb

So, No.of Frame = 2(32)

No. of Pages Of the Process = 2(20)


Page Table 1 size =2(20) * 4 B= 4 MB
As, it is larger than 4B(Frame size).Thus, this Page Table has to converted to pages
No. of pages of the Page Table 2 (Outer Page Table)
= 2(22)*2(-12)= 2(10) pages
So, Size of Outer Page Table
= 2(10) * 4B = 4KB
Thus here our Outer Page Table can be stored in one frame .
Thus, we can stop here.This is Two-level Paging because here we got 2 page tables.
CS 313 – Operating System Lab Manual

Segmentation:
A process is divided into Segments. The chunks that a program is divided into which are
not necessarily all of the same sizes are called segments.
Example:

A solution to the problem is to use segmentation along with paging to reduce the
size of the page table. Traditionally, a program is divided into four segments:
code,data stack,heap.
CS 313 – Operating System Lab Manual

LAB TASKS
Task (15 marks)
Write C++ program to simulate two-level paging technique using the above example.

(Paste your code here)

Extra Task (15 marks)


Write C++ program to simulate Virtual memory segmentation technique using the above
example.

(Paste your code here)


CS 313 – Operating System Lab Manual

LAB NO. 13
PAGE FAULTS
Following are the lab objectives:
1. To simulate the First In First Out (FIFO) Page
replacement algorithm.
Lab 2. To simulate the Optimal Page replacement algorithm.
Objectives 3. To simulate the Least Recently Used replacement
algorithm.

Roll No. Student Name


Obtained
Marks Comments
Marks
Task 1 15
Task 2 15
Total
30
Marks

Lab Instructor
CS 313 – Operating System Lab Manual

Lab Objectives and CLOs Mapping

Lab CLOs
Objectives a b c
1
2
3

Instructions
▪ This is individual Lab work/task.
▪ Complete this lab work within lab timing.
▪ Discussion with peers is not allowed.
▪ You can consult any book, notes & Internet.
▪ Copy paste from the Internet will give you negative marks.
▪ Lab work is divided into small tasks, completing all tasks sequentially.
▪ Show the solution of each lab task to your Lab Instructor.
▪ In-Lab Exercises/Tasks
▪ Write your code at provided space after each question
▪ You need to upload code for all tasks at LMS.
CS 313 – Operating System Lab Manual

Page Fault – A page fault happens when a running program accesses a memory page that
is mapped into the virtual address space, but not loaded in physical memory.
Page Replacement Algorithms :
1. First In First Out (FIFO) :
This is the simplest page replacement algorithm. In this algorithm, the operating system
keeps track of all pages in the memory in a queue, the oldest page is in the front of the
queue.
Example: Consider page reference string 1, 3, 0, 3, 5, 6 with 3 page frames.Find number
of page faults.
Implementation – Let capacity be the number of pages that memory can hold. Let set be
the current set of pages in memory.
1- Start traversing the pages.
i) If the set holds less pages than capacity.
a) Insert page into the set one by one until
the size of set reaches capacity or all
page requests are processed.
b) Simultaneously maintain the pages in the
queue to perform FIFO.
c) Increment page fault
ii) Else
If the current page is present in set, do nothing.
Else
a) Remove the first page from the queue
as it was the first to be entered in
the memory
b) Replace the first page in the queue with
the current page in the string.
CS 313 – Operating System Lab Manual

c) Store the current page in the queue.


d) Increment page faults.
2. Return page faults.

2. Optimal Page replacement :


In this algorithm, pages are replaced which would not be used for the longest duration of
time in the future.
Example: Consider the page references 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, with 4 page
frames. Find number of page faults.
Implementation:
1. If the referred page is already present, increment hit count.
2. If not present, find a page that is never referenced in future. If such a page
exists, replace this page with a new page. If no such page exists, find a page
that is referenced farthest in future. Replace this page with a new page.

3. Least Recently Used :


In this algorithm page will be replaced with which is least recently used.
Example: Consider the page reference string 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2 with 4 page
frames.Find number of page faults.
Implementation:
Let capacity be the number of pages that
memory can hold. Let set be the current
set of pages in memory.
1- Start traversing the pages.
i) If the set holds less pages than capacity.
a) Insert page into the set one by one until
the size of set reaches capacity or all
CS 313 – Operating System Lab Manual

page requests are processed.


b) Simultaneously maintain the recent occurred
index of each page in a map called indexes.
c) Increment page fault
ii) Else
If the current page is present in set, do nothing.
Else
a) Find the page in the set that was least
recently used. We find it using an index array.
We basically need to replace the page with
minimum index.
b) Replace the found page with the current page.
c) Increment page faults.
d) Update index of current page.

2. Return page faults.


CS 313 – Operating System Lab Manual

LAB TASKS
Task 01: (15 marks)
Write C++ program to simulate First in First Out (FIFO) Page Replacement Algorithm using the
above example.

(Paste your code here)

Task 02: (15 marks)


Write C++ program to simulate Optimal Page Replacement algorithm using the above example .

(Paste your code here)

Extra Task (15 marks)


Write C++ program to simulate the Least Recently Used algorithm using the above example .

(Paste your code here)


CS 313 – Operating System Lab Manual

LAB NO. 14
STORAGE MANAGEMENT AND FILE SYSTEM
Following are the lab objectives:
1. To simulate file organization techniques in Single level
directory.
Lab 2. To simulate file organization techniques in Two level
Objectives directory.

Roll No. Student Name


Obtained
Marks Comments
Marks
Task 1 15
Task 2 15
Total
30
Marks

Lab Instructor
CS 313 – Operating System Lab Manual

Lab Objectives and CLOs Mapping

Lab CLOs
Objectives a b c
1
2
3

Instructions
▪ This is individual Lab work/task.
▪ Complete this lab work within lab timing.
▪ Discussion with peers is not allowed.
▪ You can consult any book, notes & Internet.
▪ Copy paste from the Internet will give you negative marks.
▪ Lab work is divided into small tasks, completing all tasks sequentially.
▪ Show the solution of each lab task to your Lab Instructor.
▪ In-Lab Exercises/Tasks
▪ Write your code at provided space after each question
▪ You need to upload code for all tasks at the Learning Management System (LMS).
CS 313 – Operating System Lab Manual

Single level Directory:


It is the simplest of all directory structures, in this the directory system having only one
directory, consisting of all files. Sometimes it is said to be the root directory

Implementation:
1:Start
2: Initialize values gd=DETECT,gm,count,i,j,mid,cir_x;
Initialize character array fname[10][20];
3: Initialize graph function as
Initgraph(& gd, &gm," c:/tc/bgi");
Clear device();
4:set background color with setbkcolor();
5:read the number of files in variable count.
6:if check i<count
7: for i=0 & i<count
i increment;
Cleardevice();
setbkcolor(GREEN);
read file name;
setfillstyle(1,MAGENTA);
8: mid=640/count;
cir_x=mid/3;
bar3d(270,100,370,150,0,0);
settextstyle(2,0,4);
settextstyle(1,1);
outtextxy(320,125,"rootdirectory");
setcolor(BLUE);
i++;
9:for j=0&&j<=i&&cir_x+=mid
j increment;
line(320,150,cir_x,250);
CS 313 – Operating System Lab Manual

fillellipse(cir_x,250,30,30);
outtextxy(cir_x,250,fname[i]);
10: End

Two-Level Directory:
In the two-level directory structure, each user has their own user files directory (UFD).
The UFDs have similar structures, but each lists only the files of a single user. System's
master file directory (MFD) is searched whenever a new user id=s logged in.

Lab Task 01:. Write C++ program to simulate Single level directory algorithm using the above
example. (10)

Lab Task 02:Write C++ program to simulate Two- level directory algorithm using the above
example. (10)

Extra Task: Write a C++ program to simulate a two-level directory using the example given
below.
CS 313 – Operating System Lab Manual

You might also like