0% found this document useful (0 votes)
219 views36 pages

Lab Assignment 5 PDF

The document provides instructions for laboratory classes on operating systems. It lists general do's and don'ts for students in the lab, such as signing in, maintaining silence, and properly shutting down systems. It also outlines 15 experiments on UNIX/Linux commands and concepts like processes, scheduling, semaphores, memory management and file allocation. The experiments cover basic commands, text editing and searching, file permissions, shells and process related system calls.

Uploaded by

Ankit Srivastava
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
219 views36 pages

Lab Assignment 5 PDF

The document provides instructions for laboratory classes on operating systems. It lists general do's and don'ts for students in the lab, such as signing in, maintaining silence, and properly shutting down systems. It also outlines 15 experiments on UNIX/Linux commands and concepts like processes, scheduling, semaphores, memory management and file allocation. The experiments cover basic commands, text editing and searching, file permissions, shells and process related system calls.

Uploaded by

Ankit Srivastava
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 36

IT/V SEM OS LAB

OPERATING SYSTEMS LABORATORY


LABORATORY MANUAL
FOR V SEMESTER B.Tech / IT
ACADEMIC YEAR: 2015 - 2016
(FOR PRIVATE CIRCULATION ONLY)
IIIT UNIVERSITY, BHUBANESWAR

NAME:……………………………………
REG.NO:…………………………………
BATCH :…………..………………………

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


INTERNATIONAL INSTITUTE OF INFORMATION TECHNOLOGY,
BHUBANESWAR, ODISHA.

1
IT/V SEM OS LAB

GENERAL INSTRUCTIONS FOR LABORATORY CLASSES

DO’S
 Without Prior permission do not enter into the Laboratory.
 While entering into the LAB students should wear their ID cards.
 The Students should come with proper uniform.
 Students should sign in the LOGIN REGISTER before entering into the
laboratory.
 Students should come with observation and record note book to the
laboratory.
 Students should maintain silence inside the laboratory.
 After completing the laboratory exercise, make sure to shutdown the system
properly.

DONT’S
 Students bringing the bags inside the laboratory..
 Students wearing slippers/shoes insides the laboratory.
 Students using the computers in an improper way.
 Students scribbling on the desk and mishandling the chairs.
 Students using mobile phones inside the laboratory.
 Students making noise inside the laboratory.

2
IT/V SEM OS LAB

OPERATING SYSTEMS LABORATORY


(Implement the following on LINUX or other Unix like platform. Use C for high level language
implementation)

LIST OF EXPERIMENTS

01. To Study basic commands (Part I) of UNIX.


02. To Study basic commands (Part II) of UNIX.

03. To Study Shell Scripting.

04. To write c program to implement the Process system calls.


05. Given the list of processes, their CPU burst times and arrival times,
display/print the Gantt chart for FCFS, SJF, Round Robin and pre-emptive priority
scheduling. For each of the scheduling policies, compute and print the average
waiting time and average turnaround time. (2 sessions)

06. Implement the Producer – Consumer problem using semaphores (using UNIX
system calls).

07. Implement the dining philosopher problem using threads.

08. Implement Banker’s Algorithm for multiple resources.

09. Implement memory management schemes such as first fit, best fit, Paging and
Segmentation.

10. Implement Page replacement policies like optimal, LRU, and FIFO.

11. Implement Inter Process Communication using shared memory, pipes or


message queue.
12. Implement any file allocation technique such as Linked, Indexed, contiguous.

3
IT/V SEM OS LAB

LAB ASSIGNMENT 1:
Title: To Study basic commands (Part I) of UNIX.
Description:
I file and Directory Related commands
1) pwd
This command prints the current working directory
2) ls
This command displays the list of files in the current working directory.
$ls –l Lists the files in the long format
$ls –t Lists in the order of last modification time
$ls –d Lists directory instead of contents
$ls -u Lists in order of last access time
3) cd
This command is used to change from the working directory to any other directory
specified.
$cd directoryname
4) cd ..
This command is used to come out of the current working directory.
$cd ..
5) mkdir
This command helps us to make a directory.
$mkdir directoryname
6) rmdir
This command is used to remove a directory specified in the command line. It requires
the specified directory to be empty before removing it.
$rmdir directoryname
7) cat
This command helps us to list the contents of a file we specify.
$cat [option][file]
cat > filename – This is used to create a new file.
cat >>filename – This is used to append the contents of the file
8) cp
This command helps us to create duplicate copies of ordinary files.
$cp source destination
9) mv
This command is used to move files.
$mv source destination
10) ln
This command is to establish an additional filename for the same ordinary file.
$ln firstname secondname
11) rm
This command is used to delete one or more files from the directory.
$rm [option] filename
$rm –i Asks the user if he wants to delete the file mentioned.

4
IT/V SEM OS LAB

$rm –r Recursively delete the entire contents of the directory as well as the directory
itself.
II) Process and status information commands
1) who
This command gives the details of who all have logged in to the UNIX system currently.
$ who
2) who am i
This command tells us as to when we had logged in and the system’s name for the
connection being used. $who am i
8
3) date
This command displays the current date in different formats.

4) echo
This command will display the text typed from the keyboard.
$echo
Eg: $echo Have a nice day
O/p Have a nice day
S No. Description Command
01 Create a File
02 Display the contents of a file cat
03 Make Directory mkdir
04 Make Subdirectory Mkdir –p <dir1/dir2>

05 Goto root Directory Cd


06 Moving a file from one place to another Mv

07 Display or Set Date date


08 Delete the file without confirmation rm
09 Delete the empty Directory from the rmdir
system
10 List the file in your current working ls
directory
11 Display the present working Directory pwd

12 Display list of users logged in the local who


system
13 Display the Calendar cal
14 Display the message echo
15 Copy a file cp

Result: Basic UNIX commands studied

5
IT/V SEM OS LAB

LAB ASSIGNMENT 2:
Title: To Study commands (PART II) of UNIX.

Description:
I Text related commands
1. head
This command displays the initial part of the file. By default it displays first ten lines of
the file.
$head [-count] [filename]
2. tail
This command displays the later part of the file. By default it displays last ten lines of the
file.
$tail [-count] [filename]
3. wc
This command is used to count the number of lines, words or characters in a file.
$wc [-lwc] filename
4. find
The find command is used to locate files in a directory and in a subdirectory.
The –name option
This lists out the specific files in all directories beginning from the named directory. Wild
cards can be used.
The –type option
This option is used to identify whether the name of files specified are ordinary files or
directory files. If the name is a directory then use “-type d “and if it is a file then use “-
type f”.
The –mtime option
This option will allow us to find that file which has been modified before or after a
specified time. The various options available are –mtime n(on a particular day),-mtime
+n(before a particular day),-mtime –n(after a particular day)
The –exec option
This option is used to execute some commands on the files that are found by the find
command.

II File Permission commands


1) chmod
Changes the file/directory permission mode: $ chmod 777 file1
Gives full permission to owner, group and others
$ chmod o-w file1
Removes write permission for others.
III Useful Commands:
1) exit - Ends your work on the UNIX system.
2) Ctrl-l or clear
Clears the screen.
3) Ctrl-c
Stops the program currently running.

6
IT/V SEM OS LAB

4) Ctrl-z
Pauses the currently running program.
5) man COMMAND
Looks up the UNIX command COMMAND in the online manual pages.
6) history
List all commands typed so far.
7) more FILE
Display the contents of FILE, pausing after each screenful.
There are several keys which control the output once a screenful has been printed.
<enter> Will advance the output one line at a time.
<space bar> Will advance the output by another full screenful.
"q" Will quit and return you to the UNIX prompt.
8) less FILE
"less" is a program similar to "more", but which allows backward movement in the file as
well as forward movement.
9) lpr FILE
To print a UNIX text or PostScript file, type the following command at the system
prompt:

Meta characters
Some special characters, called met characters may be used to specify multiple filenames. These
characters substitute filenames or parts of filenames.
The “*”
This character is used to indicate any character(s)
$ cat ap*
This displays the contents of all files having a name starting with ap followed by any number of
characters.
The “?” This character replaces any one character in the filename.
$ ls ?st
list all files starting with any character followed by st.
The [] These are used to specify range of characters.
$ ls [a-z]pple
Lists all files having names starting with any character from a to z.
Absolute path and relative path
Generally if a command is given it will affect only the current working directory. For example
the following command will create a directory named curr in the current working directory.
$ mkdir curr
The directory can also be created elsewhere in the file system using the absolute and relative
path.If the path is given with respect to the root directory then it is called full path or absolute
path $ mkdir /home/it2006/it2k601/curr
The full paths always start with the /, which represents the root directory.

If the path is given with respect to the current working directory or parent directory then it is
called relative path.
$ mkdir ../curr
The above command will create a directory named curr in the parent directory.

7
IT/V SEM OS LAB

$ mkdir ./first/curr
The above command will create a directory named curr inside first directory, where the directory
first is located in the current working directory.
Note “.” Represents current directory and “...” represents parent directory.
PIPES AND FILTERS
In UNIX commands were created to perform single tasks only. If we want to perform multiple
tasks we can go for pipes and filters.
PIPES
A pipe is a mechanism, which takes the output of a command as its input for the next command.
$who | wc –l
$cat text.c | head –3
FILTERS
Filters are used to extract the lines, which contain a specific pattern, to arrange the contents of a
file in a sorted order, to replace existing characters with some other characters, etc.
1.Sort filter
The sort filter arranges the input taken from the standard input in alphabetical order. The sort
command when used with “-r” option will display the input taken from the keyboard in the
reverse alphabetical order. When used with “-n” option arranges the numbers, alphabets and
special characters according to their ASCII value. If we want to sort on any one field, then sort
provides us with an option called “+pos1 –pos2” option.
2.Grep filter
This command is used to search for a particular pattern from a file or from standard input and
display those lines on the standard output. Grep stands for “Global search for regular
expression”.
There are various options available with grep command.
-v displays only those lines which do not match the pattern specified.
-c displays only the count of those lines which match the pattern specified
-n displays matched lines with line numbers
-i displays matched pattern ignoring case distinction
3.Uniq filter
The uniq filter compares adjacent lines in the sorted input file and when used with different
options displays single and multiple occurrences.
-d displays only the lines which are duplicated in the input file.
-u displays only the lines with single occurrences.
4.Pg and more filter
These commands display the output of the command on the screen page by page. The difference
between pg and more filters is that the viewing screen of the latter can be done by pressing space
bar while that of the former is done by pressing enter.
5.Cut command
One particular field from any file or from output of any command can be extracted and displayed
using this cut command. One particular character can also be extracted using the –c option of this
command.
6.Tr command
This command is used to translate characters taken from the standard input. This command when
used with “-s” option is used to squeeze multiple spaces into a single space.

8
IT/V SEM OS LAB

LAB ASSIGNMENT 3:
Title: To Study Shell Scripting.

Description:
Introduction
Shells are interactive, which means that they can accept commands from you via keyboard and
execute them. It is possible to store a command in a sequential manner to a text file and tell the
shell to execute the file, instead of entering the commands one by one. This is known as a shell
script. The shell also incorporates powerful programming language that enables the user to
exploit the full power and versatility of UNIX. Shell scripts are powerful tool for invoking and
organizing UNIX commands. The shell's more advanced script can do decision sequences and
loops thereby performing almost any programming task. A script can provide interaction,
interrupts and error handling and status report just like UNIX commands.
Why to use Shell Script
 Shell Script can take input from user, file and output them onto screen.
 Useful to create our own commands.
 Save lots of time.
 To automate some task of day-to-day.10
 System administration can automate.

The three widely used UNIX shells are Bourne shell, C shell and Korn shell. All the shells
supports processes, pipes, directories and other features of UNIX. It may happen that the shell
scripts written for one shell may not work on other. This is because the different shells use
different mechanism to execute the commands in the shell script.

Basic of Shell script :


Create a file and write all UNIX commands that you want to execute and save that file with
extension .sh.
Example: Create a file script1.sh and type following commands in it.

ls
who

Use the following command to run this script.


Bash$ sh script1.sh
1) Displaying message on the screen echo message
2) reading input in a variable
read m1,m2,m3
where m1 m2 and m3 are variables.
3) Display value of a variable
echo $m1 $m2 $m3
4) Assigning value to a variable
m1=10 m2=20 m3=30
5) Comments in Shell
# this is a comment

9
IT/V SEM OS LAB

6) Performing arithmetic operations


Because all shell variables are string variables. If we want to perform arithmetic operation on
these variables have to use command expr.
a=20 b=30
echo `expr $a + $b`
echo `expr $a \* $b`
echo `expr $a / $b`
7) Control Instructions in shell
 if-then-fi
if control command
then
# statements
Fi

 if-then-else-fi
if control command
then
#statements
else
# statements
Fi

 using test
this command translate the result into the language of true and false
if test condition
then
# statements
fi
e.g. if test $num -lt 6
then
echo “value is less than 6”
fi
-gt : greate than
-lt : less than
-ge : Greater than or equal to
-le : Less than or equal to
-ne : Not equal to
-eq : equal to

 Logical operators:
-a (AND)
-o (OR)
! (NOT)

 _Loops
while [condition]

10
IT/V SEM OS LAB

do
#statements
done
until [condition]
do
# statements
done
for counter in *
do
#statements
done

Result: Shell Script Studied Successfully.

11
IT/V SEM OS LAB

LAB ASSIGNMENT 4:
Title: To write c program to implement the Process system calls.

Description

 The fork () function shall create a new process. The new process (child process) shall be
an exact copy of the calling process (parent process). The child process shall have a
unique process ID.
 The exec family of functions shall replace the current process image with a new process
image. The new image shall be constructed from regular, executable file called the new
process image file
 The exit status will be n, if specified. Otherwise, the value will be the exit value of the
last command executed, or zero if no command was executed. When exit is executed in a
trap action, the last command is considered to be the command that executed immediately
preceding the trap action
 The readdir() function returns a pointer to a parent structure representing the next
directory entry in the directory stream pointed to by dir.
 The opendir() function opens a directory stream corresponding to the directory name,
and returns a pointer to the directory stream. The stream is positioned at the first entry in
the directory

Syntaxes & Keywords


Fork:
#include<unistd.h>
pid_t fork(void);

execl:
#include<unistd.h>
extern char **environ;
int execl(const char *path, const char *arg(), …/*, (char *)0 */);

exit:
#include<stdlib.h>
void exit(int status);

wait:
#include<sys/types.h>
#include<sys/wait.h>
pid_t wait(int *stat_loc);

Readdir() :
#include <sys/types.h>
#include <dirent.h>
struct dirent *readdir(DIR *dir);

12
IT/V SEM OS LAB

Opendir():
#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *name);

Advantage
Each device can be accessed as though it was a file in the file system. Since most of the kernel
deals with devices through this file interface, it is relatively easy to add a new device driver by
implementing the hardware-specific code to support this abstract file interface. Therefore, this
benefits the development of both user program code, which can be written to access devices and
files in the same manner, and device driver code, which can be written to support a well-defined
API.
Disadvantage
The disadvantage with using the same interface is that it might be difficult to capture the
functionality of certain devices within the context of the file access API, thereby either resulting
in a loss of functionality or a loss of performance. Some of this could be overcome by the use of
ioctl operation that provides a general purpose interface for processes to invoke operations on
devices.
Applications
To serve an average Web page that includes five external links (for instance images), a Web
server executes 12 read and write system calls. Thus a busy Web server serving 1000 hits per
second will have executed more than one

Facilities Required and Procedure

a) Facilities required to do the experiment:

b) Procedure for doing the experiment:


Step Details of the step
no.
1 Open the VI text editor
2 Create a sub directory under home directory
3 Type the codes using C language
4 Use the system calls such as fork(), stat(), getpid(), wait(), exit()
5 Save the file using „filename.c‟.
6 Compile the program using „gcc filename.c‟.
7 Execute the program using „./a.out‟.

Result: The program for process system call has been executed and shown the result as above.

13
IT/V SEM OS LAB

QUESTIONS AND ANSWERS:

1. What is an Operating system?


An operating system is a program that manages the computer hardware. It also provides a basis
for application programs and act as an intermediary between a user of a computer and the
computer hardware. It controls and coordinates the use of the hardware among the various
application programs for the various users.

2. What is the use of fork and exec system calls?


Fork is a system call by which a new process is created. Exec is also a system call, which is used
after a fork by one of the two processes to replace the process memory space with a new
program.

14
IT/V SEM OS LAB

LAB ASSIGNMENT 5:
Title: To write a program to implement the following process scheduling algorithms
1) First Come First Serve
2) Shortest Remaining Job First
3) Round Robin
4) Pre-emptive Priority Scheduling

Description:
Scheduling algorithms are used when more than one process is executable and the OS has to
decide which one to run first.
Terms used
1) Submit time: The process at which the process is given to CPU
2) Burst time: The amount of time each process takes for execution
3) Response time: The difference between the time when the process starts execution and the
submit time.
4) Turnaround time: The difference between the time when the process completes execution and
the submit time.

First Come First Serve (FCFS)


The processes are executed in the order in which they have been submitted.

Facilities Required and Procedure

a) Facilities required to do the experiment:

b) Procedure for doing the experiment:

15
IT/V SEM OS LAB

Shortest Job First (SJF)


The processes are checked at each arrival time and the process which has the shortest remaining
burst time at that moment gets executed first. This is a preemptive & non-preemptive algorithm.

a) Procedure for doing the experiment:

Round Robin
Each process is assigned a time interval called its quantum(time slice) If the process is still
running at the end of the quantum the CPU is preempted and given to another process, and this
continues in circular fashion, till all the processes are completely executed.

a) Procedure for doing the experiment:

Step Details of the step


no.

1 Start the program.


2 Get the number of processes, their burst time and time slice for each process.
3 Calculate the total burst time.
4 To check whether the burst time of process is less then the time slice, the
required time only allotted to the process.
5 If the burst time of process is greater than the time slice one time slice is
allotted for the process and burst time is subtracted by one time slice.
6 Step 4 and 5 is repeated up to process burst time is 0.
7 The waiting time and turn around time for all the processes are summed and
then the average waiting time and turn around time are calculated.
8 The average waiting time and turn around time are displayed.
9 Stop the program.

Preemptive Priority Scheduling


Each process is assigned a priority and executable process with highest priority is allowed to run

a) Procedure for doing the experiment:

16
IT/V SEM OS LAB

Result: Various process scheduling algorithms have been studied successfully.

QUESTIONS AND ANSWERS:

1. Define dispatcher and its functions?


i. Switching context ii.Switching to user mode
iii. Jumping to the proper location in the user program to restarts the program

2. Define dispatch latency?


The time taken for the dispatcher to stop one process and start another running process is known
as dispatch latency.

17
IT/V SEM OS LAB

LAB ASSIGNMENT 6:
Title: Implementation of Producer Consumer Problem Using Semaphore.

Description:
Producer-Consumer problem (also known as the bounded-buffer problem) is a classical
example of a multi-process synchronization problem. The problem describes two processes, the
producer and the consumer, who share a common, fixed-size buffer. The producer's job is to
generate a piece of data, put it into the buffer and start again. At the same time the consumer is
consuming the data (i.e. removing it from the buffer) one piece at a time. The problem is to make
sure that the producer won't try to add data into the buffer if it's full and that the consumer won't
try to remove data from an empty buffer.
The solution for the producer is to go to sleep if the buffer is full. The next time the consumer
removes an item from the buffer, it wakes up the producer who starts to fill the buffer again. In
the same way, the consumer goes to sleep if it finds the buffer to be empty. The next time the
producer puts data into the buffer, it wakes up the sleeping consumer. The solution can be
reached by means of inter-process communication, typically using semaphores. An inadequate
solution could result in a deadlock where both processes are waiting to be awakened. The
problem can also be generalized to have multiple producers and consumers.

Using semaphores:
Semaphores solve the problem of lost wakeup calls. In the solution below we use two
semaphores, fillCount and emptyCount, to solve the problem. fillCount is incremented and
emptyCount decremented when a new item has been put into the buffer. If the producer tries to
decrement emptyCount while its value is zero, the producer is put to sleep. The next time an item
is consumed, emptyCount is incremented and the producer wakes up. The consumer works
analogously.

semaphore fillCount = 0
semaphore emptyCount = BUFFER_SIZE
procedure producer() {
while (true) {
item = produceItem()
down(emptyCount)
putItemIntoBuffer(item)
up(fillCount)
}
}
procedure consumer() {
while (true) {
down(fillCount)
item = removeItemFromBuffer()
up(emptyCount)
consumeItem(item)
}}

18
IT/V SEM OS LAB

The solution above works fine when there is only one producer and consumer. Unfortunately,
with multiple producers or consumers this solution contains a serious race condition that could
result in two or more processes reading or writing into the same slot at the same time. To
understand how this is possible, imagine how the procedure putItemIntoBuffer() can be
implemented. It could contain two actions, one determining the next available slot and the other
writing into it. If the procedure can be executed concurrently by multiple producers, then the
following scenario is possible:
1. Two producers decrement emptyCount
2. One of the producers determines the next empty slot in the buffer
3. Second producer determines the next empty slot and gets the same result as the first producer
4. Both producers write into the same slot

To overcome this problem, we need a way to make sure that only one producer is executing
putItemIntoBuffer() at a time. In other words we need a way to execute a critical section with
mutual exclusion. To accomplish this we use a binary semaphore called mutex. Since the value
of a binary semaphore can be only either one or zero, only one process can be executing between
down(mutex) and up(mutex). The solution for multiple producers and consumers is shown
below.
semaphore mutex = 1
semaphore fillCount = 0
semaphore emptyCount = BUFFER_SIZE
procedure producer() {
while (true) {
item = produceItem()
down(emptyCount)
down(mutex)
putItemIntoBuffer(item)
up(mutex)
up(fillCount)
}
up(fillCount) //the consumer may not finish before the producer.
}
procedure consumer() {
while (true) {
down(fillCount)
down(mutex)
item = removeItemFromBuffer()
up(mutex)
up(emptyCount)
consumeItem(item)
}
}

19
IT/V SEM OS LAB

Facilities Required And Procedure:


a) Facilities required to do the experiment:

b) Procedure for doing the experiment:

Step Details of the step


no.
1 Declare variable for producer & consumer as pthread-t-tid produce tid consume.
2 Declare a structure to add items, semaphore variable set as struct.
3 Read number of items to be produced and consumed.
4 Declare and define semaphore function for creation and destroy.
5 Define producer function.
6 Define producer function.
7 Call producer and consumer.
8 Stop the execution.

Result: Thus the producer consumer program was executed and verified successfully.

QUESTIONS AND ANSWERS

1. What is a semaphore?
A semaphore 'S' is a synchronization tool which is an integer value that, apart from initialization,
is accessed only through two standard atomic operations; wait and signal. Semaphores can be
used to deal with the n process critical section problem. It can be also used to solve various
synchronization problems. The classic definition of 'wait' wait (S) {while (S<=0) ; S-- ;} the
classic definition of 'signal' signal (S) {S++ ;}

2. Define busy waiting and spin lock.


When a process is in its critical section, any other process that tries to enter its critical section
must loop continuously in the entry code. This is called as busy waiting and this type of
semaphore is also called a spin lock, because the process while waiting for the lock.

3. What is a thread?
A thread otherwise called a lightweight process (LWP) is a basic unit of CPU utilization, it
comprises of a thread id, a program counter, a register set and a stack. It shares with other
threads belonging to the same process its code section, data section, and operating system
resources such as open files and signals.

20
IT/V SEM OS LAB

LAB ASSIGNMENT 7:
Title: Write a Program to Implement Producer Consumer Problem (Using Thread)

Description:
The producer-consumer problem (Also called the bounded-buffer problem.) illustrates the need
for synchronization in systems where many processes share a resource. In the problem, two
processes share a fixed-size buffer. One process (producer) produces information and puts it in
the buffer, while the other process (consumer) consumes information from the buffer. These
processes do no take turns accessing the buffer, they both work concurrently. Herein lies the
problem. What happens if the producer tries to put an item into a full buffer? What happens if the
consumer tries to take an item from an empty buffer?
In order to synchronize these processes, we will block the producer when the buffer is full, and
we will block the consumer when the buffer is empty. So the two processes, Producer and
Consumer, should work as follows:

Data Structures and Functions

The main data structures used here are: Arrays


The arrays represent the philosophers and corresponding chopsticks for them. Each element in
the philosopher’s array corresponds to a thread and each element in the chopstick’s array
corresponds to a mutex variable.

The functions used here are:


1. pthread_mutex_init (&mutex, NULL) – initialization of mutex variable
2. pthread_mutex_lock (&mutex) – attempt to lock a mutex
3. pthread_mutex_unlock (&mutex) – unlock a mutex
4. pthread_create (ptr to thread, NULL, (void*) func, (void*) )
5. pthread_join (ptr to thread, &msg)-This function will make the main program wait until
the called thread is finished executing it’s task.
6. pthread_mutex_destroy (ptr to thread)-
7. pthread_exit(NULL)

Facilities Required And Procedure:

a) Facilities required to do the experiment:

21
IT/V SEM OS LAB

b) Procedure for doing the experiment:


Algorithm for process:

Step Details of the step


no.
1 Start.
2 Declare and initialize the thread variables ( philosophers ) as required.
3 Declare and initialize the mutex variables (chopsticks) as required.
4 Create the threads representing philosophers.
5 Wait until the threads finish execution.
6 Stop.

Algorithm for thread (philosopher i) function:

Step Details of the step


no.
1 Start.
2 Philosopher i is thinking .
3 Lock the left fork spoon.
4 Lock the right fork spoon.
5 Philosopher i is eating.
6 Sleep
7 Release the left fork spoon.
8 Release the right fork spoon.
9 Philosopher i Finished eating.
10 Stop.

Result: Producer consumer problem is solved successfully using POSIX threads and semaphore.

QUESTIONS AND ANSWERS


1. What is race condition?
A race condition or race hazard is the behavior of an electronic or software system where
the output is dependent on the sequence or timing of other uncontrollable events. It becomes
a bug when events do not happen in the order the programmer intended. The term originates
with the idea of two signals racing each other to influence the output first. Race can occur in
electronics systems, especially logic circuits, and in computer software, especially
multithreaded or distributed programs.

2. What is multi-threading? Write advantages of multi-threading.

22
IT/V SEM OS LAB

A thread is a sequence of control within a process. A single-threaded process follows a


single sequence of control while executing. An MT process has several sequences of
control, thus is capable of several independent actions at the same time. When multiple
processors are available, those concurrent but independent actions can take place in parallel.

Some of the most important benefits of MT are:

 Improved throughput. Many concurrent compute operations and I/O requests within a
single process.
 Simultaneous and fully symmetric use of multiple processors for computation and I/O
 Superior application responsiveness. If a request can be launched on its own thread,
applications do not freeze or show the "hourglass". An entire application will not block,
or otherwise wait, pending the completion of another request.
 Improved server responsiveness. Large or complex requests or slow clients don't block
other requests for service. The overall throughput of the server is much greater.
 Minimized system resource usage. Threads impose minimal impact on system
resources. Threads require less overhead to create, maintain, and manage than a
traditional process.
 Program structure simplification. Threads can be used to simplify the structure of
complex applications, such as server-class and multimedia applications. Simple routines
can be written for each activity, making complex programs easier to design and code, and
more adaptive to a wide variation in user demands.
 Better communication. Thread synchronization functions can be used to provide
enhanced process-to-process communication. In addition, sharing large amounts of data
through separate threads of execution within the same address space provides extremely
high-bandwidth, low-latency communication between separate tasks within an
application.

23
IT/V SEM OS LAB

LAB ASSIGNMENT 8:
Title: To implement Banker's algorithm for a multiple resources.

Description:
This uses a deadlock avoidance policy
Banker's algorithm is applied to arbitrary number of processes and arbitrary number of resource
classes each with multiple instance.
The banker's algorithm mainly consists of the following matrices:
i. The resources assigned matrix which shows the number of resources of each type are currently
assigned to each process.
ii. Resources still needed matrix indicates how many resources each process need in order to
complete. For this the process must state total resources needed before executing the program.
It also consists of three vectors.
P vector => processed resources
A vector => Available resources
E vector => Existing resources
Banker's Algorithm is a deadlock avoidance algorithm that checks for safe or unsafe state of a
System after allocating resources to a process.
When a new process enters into system, it must declare maximum no. of instances of each
resource that it may need. After requesting operating system run banker's algorithm to check
whether after allocating requested resources, system goes into deadlock state or not. If yes then it
will deny the request of resources made by process else it allocates resources to that process.
No. of requested resources (instances of each resource) may not exceed no. of available
resources in operating system and when a process completes it must release all the requested and
already allocated resources.
For implementing Banker's algorithm we should have pre-knowledge about three things:-
 How many instance of each resource a process could request. (Max)
 How many instance of each resource is already allocated to that process(Allocated)
 How many instance of each resource is already available(Available).
We can calculate need of each process from above information:-
Need=Max - Allocated.
If need<=available then request will be accepted otherwise it is denied and it will check for next
process in waiting queue.
Safe or Unsafe State:- A system is in Safe state if it’s all process finish its execution or if any
process is unable to acquire its all requested resources then system will be in Unsafe state.

Example:- To understand banker's algorithm, we consider a system with four processes P1


through P4 and three resource type A,B and C.Resource type has 10 instances, B has 5 instances
and C has total 7 instances.
Current Scenario:-

24
IT/V SEM OS LAB

Need [P2] < Available.So P2 we allocate resources to P2. After Completion of P2,
Scenario...

Now Need [P4] < Available so P4 will complete its execution .After that--

So P1 will execute and after that P3 will take resources.

Safe Sequence is: - P2 , P4, P1,P3 (we can obtain one more sequence if we allocate
resources to P3 before P1 .)

Facilities Required and Procedure:

a) Facilities required to do the experiment:

25
IT/V SEM OS LAB

b) Procedure for doing the experiment:


Algorithm for process:
Step Details of the step
no.
1 Look for a row R whose count unmet resources needs are all smaller than A. if no such
row exists; the system is deadlocked since no process can run to completion.
2 Assume the process of the row chosen requests all the resources it needs & finishes.
Mark the process as terminated & add it's resources to A vector.
3 Repeat steps i & ii, until either all processes are marked terminated

Result: Banker's algorithm to avoid deadlock is implemented successfully.

QUESTIONS AND ANSWERS

1) What are the conditions to occur a deadlock?


A deadlock situation can arise if all of the following conditions hold simultaneously in a
system
1. Mutual Exclusion: At least one resource must be held in a non-shareable mode. Only
one process can use the resource at any given instant of time.
2. Hold and Wait or Resource Holding: A process is currently holding at least one
resource and requesting additional resources which are being held by other processes.
3. No Preemption: a resource can be released only voluntarily by the process holding it.
4. Circular Wait: A process must be waiting for a resource which is being held by another
process, which in turn is waiting for the first process to release the resource. In general,
there is a set of waiting processes, P = {P1, P2, ..., PN}, such that P1 is waiting for a
resource held by P2, P2 is waiting for a resource held by P3 and so on until PN is waiting
for a resource held by P1.

2) What are the strategies to deal with deadlock?


In general, there are four strategies of dealing with deadlock problem:
1. The Ostrich Approach
Just ignore the deadlock problem altogether.
2. Deadlock Detection and Recovery
Detect deadlock and, when it occurs, take steps to recover.
3. Deadlock Avoidance
Avoid deadlock by careful resource scheduling.
4. Deadlock Prevention
Prevent deadlock by resource scheduling so as to negate at least one of the four
conditions.

26
IT/V SEM OS LAB

LAB ASSIGNMENT 9:
Title: To implement first fit, best fit, Paging and Segmentation algorithm for memory
management.

Description
A set of holes, of various sizes is scattered through the memory at any given time. When a
process arrives and needs the memory, the system searches for a hole that is large enough for this
process. The first-fit, best-fit and worst-fit are strategies used to select a free hole from the set of
available holes.
Implementation details
Free space is maintained as a linked list of nodes with each node having the starting byte address
and the ending byte address of a free block. Each memory request consists of the process-id and
the amount of storage space required in bytes. Allocated memory space is again maintained as a
linked list of nodes with each node having the process-id, starting byte address and the ending
byte address of the allocated space.
When a process finishes (taken as input) the appropriate node from the allocated list should be
deleted and this free disk space should be added to the free space list. [Care should be taken to
merge contiguous free blocks into one single block. This result in deleting more than one node
from the free space list and changing the start and end address in the appropriate node]. For
allocation use first fit, worst fit and best fit.
First-Fit
Allocate the first hole that is big enough. Searching can start either at the beginning of the set of
holes or where the previous first-fit search ended. We can stop searching as soon as we find a
free hole that is large enough.
Best-Fit
Allocate the smallest hole that is big enough. We must search the entire list unless the list is kept
ordered by size. The strategy produces the smallest leftover hole.
Worst fit
Allocate the biggest hole.

Paging
Paging is a memory allocation scheme that permits the physical address space of a process to be
non-contiguous. Physical memory is broken into fixed-sized blocks called frames. Logical
memory is also broken into blocks of same size called pages. When a process is to be executed,
its pages are loaded into any available memory frames from the secondary memory. The
secondary memory is divided into fixed size blocks of the same size as the memory frames.

27
IT/V SEM OS LAB

Mapping of physical address to logical address is shown above. Every address generated by CPU
is divided into two parts: a page number (p) and page offset (d). The page number is used as an
index into a page table. The page table contains the base address of each page in physical
memory. This base address is combined with the page offset to define the physical address that is
sent to the memory unit.

FACILITIES REQUIRED AND PROCEDURE:

a) Facilities required to do the experiment:

28
IT/V SEM OS LAB

b) Procedure for doing the experiment:


1. First fit and Best Fit

2. PAGING

Step Details of the step


no.
1 Start the program.
2 Read the base address, page size, number of pages and memory unit.
3 If the memory limit is less than the base address display the memory Limit is less than
limit.
4 Create the page table with the number of pages and page address.
5 Read the page number and displacement value.
6 If the page number and displacement value is valid, add the displacement value with the
address corresponding to the page number and display the result.
7 Display the page is not found or displacement should be less than page size.
8 Stop the program.

3. SEGMENTATION
Step Details of the step
no.
1 Start the program.
2 Read the base address, number of segments, size of each segment, memory limit.
3 If memory address is less than the base address display “invalid memory limit”.
4 Create the segment table with the segment number and segment address and display it.
5 Read the segment number and displacement.
6 If the segment number and displacement is valid compute the real address and display
the same.
7 Stop the program.

29
IT/V SEM OS LAB

Result: Memory Management techniques implemented successfully.

QUESTIONS AND ANSWERS


1. What is the main function of the memory-management unit?
The runtime mapping from virtual to physical addresses is done by a hardware device called a
memory management unit (MMU).
2. What are the common strategies to select a free hole from a set of available holes?
The most common strategies are
a. First fit
b. Best fit
c. Worst fit

30
IT/V SEM OS LAB

LAB ASSIGNMENT 10:


Title: To study various Page Replacement Policies.

Description
Page replacement algorithms are used to decide what pages to page out when a page needs to be
allocated. This happens when a page fault occurs and free page cannot be used to satisfy
allocation
FIFO:
The frames are empty in the beginning and initially no page fault occurs so it is set to minus one.
When a page fault occurs the page reference string is brought into memory. The operating
system keeps track of all the pages in memory, herby keeping track of the most recently arrived
and the oldest one. If the page in the page reference string is not in memory, the page fault is
incremented and the oldest page is replaced. If the page in the page reference string is in the
memory, take the next page without calculating the page fault. Take the next page in the page
reference string and check if the page is already present in the memory or not. Repeat the process
until all the pages are referred and calculate the page fault for all those pages in the page
reference string for the number of available frames.
LRU:
A good approximation to the optimal algorithm is based on the observation that pages that have
been heavily used in the last few instructions will probably be heavily used again in the next few.
Conversely, pages that have not been used for ages will probably remain unused for a long time.
This idea suggests a realizable algorithm: when a page fault occurs, throw out the page that has
been unused for the longest time. This strategy is called LRU (Least Recently Used) paging

EXPECTED OUTPUT AND ITS FORM


Minimizing the number of (major) page faults (situations where a page must be brought in from
disk) using LRU and FIFO.
ADVANTAGES:
Effective memory utilization
DISADVANTAGES:
Time consuming

REQUIRED AND PROCEDURE

a) Facilities required to do the experiment:

31
IT/V SEM OS LAB

b) Procedure for doing the experiment:

Step Details of the step


no.
1 Start the program.
2 Obtain the number of sequences, number of frames and sequence string from the user
3 Now when a page is not in the frame comes, increment the number of page fault and
remove the page that come in the first in FIFO algorithm
4 In LRU algorithm, when a page fault occurs, the page which most recently used is
Removed
5 Display the number of faults
6 Stop the program.

Result: The program for page replacement algorithms for memory management has been
executed and shown the results as above.

QUESTIONS AND ANSWERS

1. What is Demand paging?


Virtual memory is commonly implemented by demand paging. In demand paging, the pager
brings only those necessary pages into memory instead of swapping in a whole process. Thus it
avoids reading into memory pages that will not be used anyway, decreasing the swap time and
the amount of physical memory needed.
2. What are the various page replacement algorithms used for page replacement?
 FIFO page replacement
 Optimal page replacement
 LRU page replacement
 LRU approximation page replacement
 Counting based page replacement
 Page buffering algorithm.

32
IT/V SEM OS LAB

LAB ASSIGNMENT 11:


Title: Write a program that creates a child process. Parent process writes data to pipe and
child process reads the data from pipe and prints it on the screen.

Description:
One of the mechanisms that allow related-processes to communicate is the pipe. A pipe is a one-
way mechanism that allows two related processes (i.e. one is an ancestor of the other) to send a
byte stream from one of them to the other one. The system assures us of one thing: The order in
which data is written to the pipe, is the same order as that in which data is read from the pipe.
The system also assures that data won't get lost in the middle, unless one of the processes (the
sender or the receiver) exits prematurely.
The pipe() system call
This system call is used to create a read-write pipe that may later be used to communicate with a
process we'll fork off. The call takes as an argument an array of 2 integers that will be used to
save the two file descriptors used to access the pipe. The first to read from the pipe, and the
second to write to the pipe. Here is how to use this function:
int fd[2];
if (pipe(fd) < 0)
perror(“Error”);
If the call to pipe() succeeded, a pipe will be created, fd[0] will contain the number of its read
file descriptor, and fd[1] will contain the number of its write file descriptor. Our program first
call fork() to create a child process. One (the parent process) reads write to the pipe and child
process reads the data from the pipe ans then prints the data to the screen.
FACILITIES REQUIRED AND PROCEDURE
a) Facilities required to do the experiment:

b) Procedure for doing the experiment:

33
IT/V SEM OS LAB

Result: Thus the Pipe Processing program was executed and verified successfully.

QUESTIONS AND ANSWERS

1. What is logical address space and physical address space?


The set of all logical addresses generated by a program is called a logical address space; the
set of all physical addresses corresponding to these logical addresses is a physical address
space.

2. What is the main function of the memory-management unit?


The runtime mapping from virtual to physical addresses is done by a hardware device called
a memory management unit (MMU).

3. Define swapping.
A process needs to be in memory to be executed. However a process can be swapped
temporarily out of memory to a backing tore and then brought back into memory for
continued execution. This process is called swapping.

4. What do you mean by best fit?


Best fit allocates the smallest hole that is big enough. His entire list has to be searched, unless
it is sorted by size. His strategy produces the smallest leftover hole.

5. What do you mean by first fit?


First fit allocates the first hole that is big enough. Searching can either start at the beginning
of the set of holes or where the previous first-fit search ended. Searching can be stopped as
soon as a free hole that is big enough is found.

34
IT/V SEM OS LAB

LAB ASSIGNMENT 12:


Title: File Allocation Technique-Contiguous

Description
File Allocation Methods
One main problem in file management is how to allocate space for files so that disk space is
utilized effectively and files can be accessed quickly. Three major methods of allocating disk
space are:
* Contiguous Allocation
* Linked Allocation
* Indexed Allocation.
Each method has its advantages and disadvantages. Accordingly, some systems support all three
(e.g. Data General's RDOS). More commonly, a system will use one particular method for all
files.
Contiguous File Allocation
Each file occupies a set of contiguous block on the disk
Allocation using first fit/best fit.
A need for compaction
Only starting block and length of file in blocks are needed to work with the file
Allows random access
Problems with files that grow

ADVANTAGES:
Effective memory utilization
Each file occupies set of contiguous blocks on the disk. Random access

DISADVANTAGES:
Time consuming
Wastes lot of memory space

Facilities Required And Procedure


a) Facilities required to do the experiment:

35
IT/V SEM OS LAB

b) Procedure for doing the experiment:

Step Details of the step


no.
1 Start the process
2 Declare the necessary variables
3 Get the number of files
4 Get the total no. of blocks that fit in to the file
5 Display the file name, start address and size of the file. 6.Stop the program

Result: The program for file allocation technique has been executed and shown the results as
above.

QUESTIONS AND ANSWERS

1. What are the allocation methods of a disk space?


Three major methods of allocating disk space which are widely in use are
a. Contiguous allocation
b. Linked allocation
c. Indexed allocation

2. What is Directory?
The device directory or simply known as directory records information- such as name, location,
size, and type for all files on that particular partition. The directory can be viewed as a symbol
table that translates file names into their directory entries.
Search for a file
Create a file
Delete a file
Rename a file
List directory
Traverse the file system

36

You might also like