You are on page 1of 65

CONTENTS

Exercise
No

Title of Exercise

Page
No

CYCLE I
1

BASIC LINUX COMMANDS

SHELL PROGRAMMING

UNIX SYSTEM CALLS

UNIX I/O SYSTEM CALLS

SIMULATION OF UNIX COMMANDS(ls, grep)

CPU SCHEDULING ALGORITHMS -FCFS

CPU SCHEDULING ALGORITHMS SJF

CPU SCHEDULING ALGORITHMS Priority scheduling.


CYCLE - II

9
10
11
12
13
14

CPU SCHEDULING ALGORITHMS - Round Robin


scheduling
INTER PROCESS COMMUNICATION USING SHARED
MEMORY
INTER PROCESS COMMUNICATION USING PIPES
PRODUCER- CONSUMER PROBLEM USING
SEMAPHORES
IMPLEMENTATION OF PAGE REPLACEMENT
ALGORITHMS-FIFO
IMPLEMENTATION OF PAGE REPLACEMENT
ALGORITHMS-LRU

15

MEMORY MANAGEMENT SCHEMES - II

16

FILE ALLOCATION TECHNIQUES


AUGMENTED EXPERIMENTS

17

DEAD LOCK BANKERS ALGORITHM

18

DINING PHILOSOPHERS PROBLEM

Ex.No:1
CS 2257 OPERATING SYSTEMS LAB

Date:
1. BASIC LINUX COMMANDS
Objective
To study different types of UNIX/LINUX command syntax and check the output
of each command.
Introduction to UNIX Operating System
An Operating System (OS) can be defined as a software program designed
to control the hardware, manage the system resources and supervises interaction between
the system and its users.
Types of Operating System
Single User Operating Systems are those which are used in PCs.
Eg.DOS
Multi User Operating Systems are those which can handle
multiple users as well as peripherals simultaneously. Eg.UNIX
Functions of a Multi user Operating system
Isolating the user from the hardware.
Providing a transparent layer to communicate with hardware.
Scheduling tasks of various users.
Managing resources and allocating them to various users.
Resolving conflicting requests of various users.
Monitoring and auditing system operations
Structure of UNIX Operating System
Application
Shell
Kernel
Hardwar
e

Kernel
Kernel forms the core of the UNIX operating system. This interacts with the
hardware. It is loaded into the memory when a system is booted. Its functions are,

Memory Management
File Management and security

CS 2257 OPERATING SYSTEMS LAB

Process Scheduling and Management


Managing Hardware devices.
Allocating time for different users and processes

Shell
The Shell in one layer above the kernel. It acts as a command interpreter for the
command input by the user. The Shell takes the user command as input, interacts with the
kernel using system calls and the kernel in turn interacts with the hardware.
Additionally shell contains a programming language which enables users to write shell
scripts on their own.
The Unix Shell performs the following functions:
It acts as command interpreter
It expands the various meta characters used in file operations (like ?,[] etc)
It is responsible for redirecting the output of one command as the input of another
command in a redirection or filtering operation initiated from the command
prompt.
It is responsible for executing the shell scripts which use the programming
language of the shell
It is responsible for setting up the environment for the user.
The most important shells are the Bourne Shell, C shell Korn shell etc.
Features of UNIX OS
* Multitasking
Multitasking is the capability of the operating system to perform various tasks.ie.,
A single user can perform various tasks.
*Multi-user capability
This allows several users to use the same computer to perform their tasks.
*Security
Every user has a login name and a password. So, accessing another users data is
impossible without permission
*Portability
UNIX is portable because it is written in a high level language . So UXIX can
be run on different computers.
*Communication:
UNIX supports the following communications.
i)
Between the different terminals connected to the UNIX server.
ii)
Between the users of one computer to the users of another
Programming facility:
UNIX is highly programmable, the UNIX shell programming language has all the
necessary ingredients like conditional and control structures (Loops) and variables.

Structures of a UNIX file system

dev
/lib

lib

etc

home

bin

tmp

library files

CS 2257 OPERATING SYSTEMS LAB

/dev Contains file that link hardware devices


/tmp temporary storage of files
/home user home directories
Getting started with UNIX
Switching the system ON will provide the user with login prompt. Here we enter
the login name. Then it prompts for the password. The password is not echoed on the
screen to protect the privacy of the war. If both are correct, then we will get the S prompt.

UNIX Commands
Basic Commands
I file and Directory Related commands
1) pwd
This command prints the current working directory.
Syntax: $ pwd
2) ls
This command displays the list of files in the current working directory.
$ ls
$ ls -a: It displays all files in current directory including hidden files and
directory.
$ ls r*: It displays files whose begins with * specifies number of
characters.
$ls r?:This displays files which are having r from second character
irrespective of 1st character.
$ ls[a-m]* :It lists files whose names begin with alphabets from a to m
$ ls [!a g]*:List all files not begin with character a to g.
$ls l Lists the files in the long format. It is the way of controlling
accessibility of file each of groups and other.
$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 directory-name
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.

CS 2257 OPERATING SYSTEMS LAB

$mkdir directory-name
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 directory-name
7) cat
This command helps us to list the contents of a file we specify.
$cat [option][file]
$cat filename-Used to display the content of the 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-filename destination-filename
9) mv
This command is used to move files from one place to another place (Renaming).
$mv source-filename destination-filename
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.
$rm -r -Recursively delete the entire contents of the directory as well as
the directory itself.
12) man
This command is used to syntax help of various commands.
$man command-name
$man who

CS 2257 OPERATING SYSTEMS LAB

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 systems name for the
connection being used.
$who am i
3) date
This command displays the current date in different formats.
+%D
+%H
+%M
+%S
+%T

mm/dd/yy
Hr-00 to 23
Min-00 to 59
Sec-00 to 59
HH:MM:SS

+%w
+%a
+%h
+%r
+%y

Day of the week


Abbr.Weekday
Abbr.Month
Time in AM/PM
Last two digits of the year

4) echo
This command will display the text typed from the keyboard.
$echo
Eg: $echo Have a nice day
Output: Have a nice day
5) Executing more command at a time:
The semicolon operator overcomes the limitation of executing only one
command at a time.
SYNTAX:
$ command1; $ command2
$ pwd;who
6) tput and clear:
It clears the screen and places a$ prompt at left top corner of screen
SYNTAX:
$ tput clear
$clear

CS 2257 OPERATING SYSTEMS LAB

7) calendar : cal:
It is used to keep track of our days, it displays specified month of year.
SYNTAX:
$ cal month or year
8) calculator: bc:
Offers on online calculator and can be invoked by command be calculator
is programmable and has complex functions.
SYNTAX:
$ bc
9) Re-directing standard output to a file:
SYNTAX:
$ command > file.
The symbol > is the redirection operation. It sends the output of
the command to a file as a device such as printer, disk, type etc
SYNTAX:
$ ls >file-name
II 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]
$head -3 filename ->displays first 3 lines of the file
2. tail
This command displays the later part of the file. By default it displays last ten lines of
the file.
$tail [-count] [filename]
$tail -3 filename ->displays last 3 lines of the file
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.
$find name option
This lists out the specific files in all directories beginning from the
named directory. Wild cards can be used.

CS 2257 OPERATING SYSTEMS LAB

$find 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.
$find 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)
$find exec option
This option is used to execute some commands on the files that are
found by the find command.
$find $HOME -print will lists all files in your home directory.
$find /work -name chapter1 -print will list all files named chapter1 in /work
directory.
5) Diff
diff command will compare the two files and print out the differences between them.
Here I have two ascii text files. fileone and file two.
$diff fileone filetwo
6) Cmp command.
cmp command compares the two files. For exmaple I have two different files fileone
and filetwo.
$cmp fileone filetwo
7) Dircmp Command.
dircmp command compares two directories. If i have two directories in my home
directory named dirone and dirtwo and each has 5-10 files in it. Then
$dircmp dirone dirtwo
IV 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.

CS 2257 OPERATING SYSTEMS LAB

$ chmod o +x file1
Add execute permission to others.
V 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.
4) $Ctrl-z
Pauses the currently running program.
5) 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.
6) less

FILE
"less" is a program similar to "more", but which allows backward movement
in the file as well as forward movement.
7) lpr FILE

To print a UNIX text or PostScript file, type the following command at the system
prompt:
Meta characters
Some special characters, called metacharacters 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.

CS 2257 OPERATING SYSTEMS LAB

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.

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.
sort command sort the lines of a file or files, in alphabetical order. for example if
you have a file named testfile with these contents
zzz
aaa
1234
yuer
wer
qww
wwe

Then running
$sort testfile
will give us output of
1234
aaa
qww
wer

CS 2257 OPERATING SYSTEMS LAB

10

wwe
yuer
zzz

Options:
-b ignores leading spaces and tabs.
-c checks whether files are already sorted.
-d ignores punctuation.
-i ignore non-printing characters
-n sorts in arithmetic order.
-ofile put output in a file.
+m [-m] skips n fields before sorting, and sort upto field position m.
-r reverses the order of sort.
-u identical lines in input file appear only one time in output.

$ sort input1.txt input2.txt > output.txt


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

$ grep hello *.txt


$ grep -vi hello *.txt

If you want to search all files in an entire directory tree for a


particular pattern, you can combine grep with find using
backward single quotes to pass the output from find into grep. So
$ grep hello `find . -name "*.txt"
-print`
will search all text files in the directory tree rooted at the current
directory for lines containing the word "hello".

Syntax:
grep "word-to-find" {file-name}
3. Uniq filter

CS 2257 OPERATING SYSTEMS LAB

11

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.

removes duplicate adjacent lines from a file. This facility is


most useful when combined with sort:
uniq

$ sort input.txt | uniq > output.txt

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 filter 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.
$cut options [files]
for example if a file named testfile contains
this is firstline
this is secondline
this is thirdline

Examples:
$cut -c1,4 testfile will print this to standard output (screen)
ts
ts
ts

It is printing columns 1 and 4 of this file which contains t and s (part of this).

Options:
-c list cut the column positions identified in list.
-f list will cut the fields identified in list.
-s could be used with -f to suppress lines without delimiters.
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.
$ tr "[a-z]" "[A-Z]"
hi i am Vivek
CS 2257 OPERATING SYSTEMS LAB

12

HI I AM VIVEK
what a magic
WHAT A MAGIC Press
7) Paste Command.
Paste command merge the lines of one or more files into vertical columns
separated by a tab.
for example if a file named testfile contains
this is firstline

and a file named testfile2 contains


this is testfile2

then running this command


$paste testfile testfile2 > outputfile
will put this into outputfile
this is firstline
this is testfile2
it contains contents of both files in columns.
$who | paste - - will list users in two columns.
Options:
-d'char' separate columns with char instead of a tab.
-s merge subsequent lines from one file.

CS 2257 OPERATING SYSTEMS LAB

13

Exercises
Part- I
1. Create a directory called stud. Change to stud directory. Verify whether you have
Changed to the stud directory. Return to your original directory.
2. Create a file called top. Display the first lines from the beginning of the file and the last
three lines of the file top.
3. List the contents of a file from the fourth line to the end of the file top. List the
contents of a file from the seventh line, of the file top.
4. Create a file called list which contains sample data as follows:
1. Display the contents of the file sorted according to the marks in the descending
order.
2. Display the names of the students in the alphabetical order ignoring the cases.
3. Display the list of students who have scored marks between 50 and 80.
4. Display the list of students and their registration numbers.
5. Sort the file according to the third field and dump in to a file called code.
5. Create a file called places whose sample data is as follows and answer the questions
below.
Bombay
India
45677
Asia
Karachi
Pakistan
54876
Asia
Nairobhi
Kenya
32196
Africa
1. List the details for the countries USA, Kenya and Canada.
2. List the details for the continent asia ignoring the case.
3. Display the list of those countries whose population is between 40000 and
60000.
4. Extract the lines which end with ia.
6. Create a file emp as given and answer the questions below.
E0001: malan: mktg: 5000
E0010: balan: acct: 7000
1. Sort the file on the employee department and display the name of the
employee and the department.
2. List the employees who earn between 4000 and 6000.
3. Sort the file on the employee name in the reverse order and extract their codes
and their names.
7. What is the command to be given if we want to display the entire text of a file into
upper case?
8. Display the date in mm/dd/yy format, along with the present time in AM/PM.
9. List the various formats of date command.

CS 2257 OPERATING SYSTEMS LAB

14

EX. NO :2
DATE :

SHELL PROGRAMMING

A Linux shell is a command language interpreter, the primary purpose of which is to


translate the command lines typed at the terminal into system actions. The shell itself is a
program, through which other programs are invoked

What is a shell script ?


A shell script is a file containing a list of commands to be executed by the Linux
shell. shell script provides the ability to create your own customized Linux
commands
Linux shell have sophisticated programming capabilities which makes shell script
powerful Linux tools

How to work with shell ?


Step1:
In the dollar prompt type
$ vi < file name>
Where vi is the editor ,it will open a new window in which you can type the program you
want
Step2:
After typing the program press ESC and : together then at the bottom of the vi screen you
can see i.e. prompt .In that type as wq which means write and quit i.e. the content what is
typed will be written and saved into that file that has been created
Step3:
Once wq is typed at the : prompt ,the prompt would change to $ symbol in which you
have to do the following
$ sh < file name >
Sh
command is used to run the shell program
<file name> - is the name of the file for which the output is to be got
Basically to print a text in the your shell programs echo command is used.
To make the shell scripts interactive we can use read command.
#!/bin/sh
echo Give your name
read name
echo Hello, Good Morning $name

CS 2257 OPERATING SYSTEMS LAB

15

The variable with $ is called shell variable. We can assigh values to shell variables like
name=raji
The usage will be
$ a=20
$ echo $a
20
SYNTAX FOR LOOPING STATEMENTS
IF THEN-ELSE CONSTRUCT
if [ condition]
then
else

<action>

statements
fi (end of if)
The relational operators are
-gt
greater than
-ge
greater than and equal to
-lt
less than
-le
less than and equal to
-ne
not equal to
-eq
equal to
To compare two strings the following operators are used
str1 = str2
True if both the strings are same
str1 != str2
True if strings are different
-n string
True if the strings length is greater than zero
-z string
True if length of the string is zero
string
True if the string is not null
WHILE
while <condition>
do
<statements>
Done
CASE
Case $<option> in
1) <statements>;;
2) <statements>;;
3) ..
4)
*) <error statement>;;
Esac
[

CS 2257 OPERATING SYSTEMS LAB

16

For loop
For(( intitialization;condition;incremetation/decrementation))
Function
Function is series of instruction/commands. Function performs particular activity in shell
i.e. it had specific work to do or simply say task. To define function use following syntax:
Syntax:
function-name ( )
{
command1
command2
.....
...
commandN
return
}

Where function-name is name of you function, that executes series of commands. A


return statement will terminate the function. Example:
Type SayHello() at $ prompt as follows
$ SayHello()
{
echo "Hello $LOGNAME, Have nice computing"
return
}
To execute this SayHello() function just type it name as follows:
$ SayHello
Hello vivek, Have nice computing.

Example Scripts:

CS 2257 OPERATING SYSTEMS LAB

17

FINDING BIGGEST AMONG THREE NUMBERS


Aim:
To write a shell script to find biggest among three numbers.
Algorithm:
1) START: Take three nos as n1,n2,n3.
2) Is n1 is greater than n2 and n3, if yes print n1 is bigest no goto step 5,
otherwise goto next step
3) Is n2 is greater than n1 and n3, if yes, print n2 is bigest no goto step 5,
otherwise goto next step
4) Is n3 is greater than n1 and n2, if yes , print n3 is bigest no goto step 5,
otherwise goto next step
END

CS 2257 OPERATING SYSTEMS LAB

18

Script:

CS 2257 OPERATING SYSTEMS LAB

19

Output:

Enter the value of a:20


Enter the value of b:45
Enter the value of c:60
C is greater

Result:

CS 2257 OPERATING SYSTEMS LAB

20

FACTORIAL
Aim:
To write a shell script to calculate the factorial value of a number.
Algorithm:
1) START: read the value of n.
2) If n=1, assign i=fact =1
3) Construct a while loop as:
* Calculate fact=fact * i
* Increment I by 1 as i=i+1
4) Repeat step2 until i <n
5) Display fact as factorial value
END

CS 2257 OPERATING SYSTEMS LAB

21

Script:

CS 2257 OPERATING SYSTEMS LAB

22

Output:
enter the number
6
The factorial of 6 is 720

Result:

CS 2257 OPERATING SYSTEMS LAB

23

FIBONACCI SERIES
Aim:
To write a shell script to generate Fibonacci series.
Algorithm:
1) START: Read the value of n.
2) Assign i=3, a=c=0, b=1
3) Display a and b.
4) Construct a while loop as
* c=a+b
* Assign a=b, b=c
* Echo c and increment by 1
5) Repeat step 4 until i<=n
END

CS 2257 OPERATING SYSTEMS LAB

24

Script:

CS 2257 OPERATING SYSTEMS LAB

25

Output:
Enter the number of terms :
9
0
1
1
2
3
5
8
13
21

Result:

CS 2257 OPERATING SYSTEMS LAB

26

ARMSTRONG NUMBER
Aim:
To write a shell script to check whether the number is Armstrong or not.
Algorithm:
1) START: Read the value of n, assign d=0 and c=n.
2) Construct a while loop as
* Calculate b= n %10
* Find b= b* b *b
* n= n / 10
* d=d+s
3) Repeat step 2 until n > 0
4) Check by using if statement for c =n.
* True, display Armstrong
* False, display not Armstrong
END

CS 2257 OPERATING SYSTEMS LAB

27

Script:

CS 2257 OPERATING SYSTEMS LAB

28

Output:
Enter the number
371
371 is an Armstrong number
Enter the number
369
369 is not an Armstrong number

Result:

CS 2257 OPERATING SYSTEMS LAB

29

PALINDROME
Aim:
To write a shell script to check whether a string is a palindrome or not..
Algorithm:
1) START: Read string as str.
2) assign str to str1
3) Calculate length of str
4) Initialize while loop as
* Using temporary variable, reverse the string
* Decrement length by one
5) Check if reverse = str1
* If true, then goto step 7
6) Display string is not palindrome. Goto step 8.
7) Display string is palindrome.
END

CS 2257 OPERATING SYSTEMS LAB

30

Script:

CS 2257 OPERATING SYSTEMS LAB

31

Output:
Ente the string :
malayalam
the given string is palindrome

Result:

CS 2257 OPERATING SYSTEMS LAB

32

Ex.No:3
Date:
UNIX SYSTEM CALLS
Aim:
Write a program using the following system calls.
Description
System Calls
When a computer is turned on, the program that gets executed first is called the
``operating system.'' It controls pretty much all activity 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 "Unix".
The way that programs talk to the operating system is via ``system calls.'' A system call
looks like a procedure call (see below), but it's different -- it is a request to the
operating system to perform some activity.
getpid
Each process is identified by a unique process id (called a pid). The init process (which
is the supreme parent to all processes) posesses id 1. All other processes have some other
(possibly arbitrary) process id. The getpid system call returns the current process id as an
integer.
//
int pid = getpid();
printf(This process id is %d\n,pid);//
fork
The fork system call creates a new child process. Actually, its more accurate to
say that it forks a currently running process. That is, it creates a copy of the current
process as a new child process, and then both processes resume execution from the fork ()
call. Since it creates two processes, fork also returns two values; one to teach process. To
the parent process, fork returns the process id of the newly created child process. To the
child process, fork returns 0. The reason it returns 0 is precisely because this is an invalid
process id. You would have no way of differentiating between the parent and child
processes if fork returned an arbitrary positive integer to each. Therefore, a typical call to
fork looks something like this:
int pid;
if ( (pid = fork()) == 0 ) {
/* child process executes inside here */
}
else {
/* parent process executes inside here */
}

CS 2257 OPERATING SYSTEMS LAB

33

execvp & execlp


The exec functions (there are more than one) are a family of functions that
execute some program within the current process space. So if I write a program that calls
one of the exec functions, as soon as the function call succeeds the original process gets
replaced with whatever program I asked exec to execute. This is usually used in
conjunction with a fork call. You would typically fork a child process, and then call exec
from within the child process, to execute some other program in the new process entry
created by fork.
Directory Operations
The complex nature of Unix File system directory entries means that it is not
realistic to read such a directory using normal read() system calls and, in fact, attempting
to use read() to read a directory will fail. Instead the system call getdents() is used to read
directory entries, however this has a rather complex interface and for all normal purposes
a set of library routines is provided, these, of course, work via getdents().
There are eight such routines and two data types.
Directory handling data objects
DIR

Used to hold a pointer to an open directory. Analagous to FILE *


A structure holding information about the directory entry.

struct dirent

struct dirent
{
ino_t
off_t
ushort
char
}

d_ino; /* i-number */
d_off; /* offset into directory file */
d_reclen;
/* length of record */
d_name[1];
/* file name */

Both the above are #define'd in the standard header dirent.h. The eight routines are
Prototype

Function

DIR *opendir(const char *path)

Opens a directory

struct dirent *readdir(DIR *dirp)

Gets the next entry

Similar to readdir, takes address of


struct dirent *readdir_r(DIR *dirp,struct dirent *res) buffer as parameter. Intended for MT
applications.
long telldir(DIR *dirp)

returns current location

void seekdir(DIR *dirp,long loc)

alters current position

void rewinddir(DIR *dirp)

set current position to start

int closedir(DIR *dirp)

closes directory

CS 2257 OPERATING SYSTEMS LAB

34

Exercises:
1. Write programs using the following system calls of UNIX operating system:
fork, exec, getpid, exit, wait, close, stat, opendir, readdir
2. Write a program to list the files in the specified directory. (opendir, readdir)
3. Write a program to create a specified number of child processes (given through
command line) and display the pid of child processes with its parents pid.
Output:
Fork()system call:
HELLO
BYE
BYE
Exec() system call:
Output:
Segmentation fault
Fork() and getpid() system call:
Executing in parent process,pid=4302;
Executing in parent process,pid=5044;
Wait and execution system call:
Im the child
Im the parent
Child returned :0

CS 2257 OPERATING SYSTEMS LAB

35

Ex.No: 4
Date:
I/ O SYSTEM CALLS
Aim:
Write programs using system calls (I/O).
Description.
System Calls for I/O
There are 5 basic system calls that UNIX provides for file I/O. The system object
that is used to manipulate files is file descriptor. This is an integer number that is used by
the various I/O system calls to access a memory area containing data about the open file.
Open
Open makes a request to the operating system to use a file. The call takes two
parameters. The first argument 'path' specifies what file you would like to use, and the
'flags' and 'mode' arguments specify how you would like to use it. This call returns a file
descriptor.
The mode may be any of the following:
O_RDONLY
Open the file in read-only mode.
O_WRONLY
Open the file in write-only mode.
O_RDWR
Open the file for both reading and writing.
In addition, any of the following flags may be OR-ed with the mode flag:
O_CREAT
If the file does not exist already - create it.
O_EXCL
If used together with O_CREAT, the call will fail if the file already exists.
O_TRUNC
If the file already exists, truncate it (i.e. erase its contents).
O_APPEND
Open the file in append mode. Any data written to the file is appended at
the end of the file.
O_NONBLOCK (or O_NDELAY)
If any operation on the file is supposed to cause the calling process block,
the system call instead will fail, and errno be set to EAGAIN. This requires
caution on the part of the programmer, to handle these situations properly.
O_SYNC
Open the file in synchronous mode. Any write operation to the file will
block until the data is written to disk. This is useful in critical files (such as
database files) that must always remain in a consistent state, even if the system
crashes in the middle of a file operation.
Close
Close() tells the operating system that you are done with a file descriptor. The OS
can then reuse that file descriptor. The usage is
Close(file descriptor)

CS 2257 OPERATING SYSTEMS LAB

36

Read
Read() tells the operating system to read "size" bytes from the file opened in file
descriptor "fd", and to put those bytes into the location pointed to by "buf". It returns how
many bytes were actually read. The prototype is
int read(fd, buf, size)
Write
Write() is just like read(), only it writes the bytes instead of reading them. It
returns the number of bytes actually written, which is almost invariably "size".
rename
The rename() system call may be used to change the name (and possibly the
directory) of an existing file. It gets two parameters: the path to the old location of the file
(including the file name), and a path to the new location of the file (including the new file
name). If the new name points to an already existing file, that file is deleted first. We are
allowed to name either a file or a directory.
/* rename the file 'logme' to 'logme.1' */
if (rename("logme", "logme1") == -1) {
perror("rename (1):");
exit(1);
}
delete
Deleting a file is done using the unlink() system call. This one is very simple:
/* remove the file "/tmp/data" */
if (unlink("/tmp/data") == -1) {
perror("unlink");
exit(1);
}
Exercises:
1. Write a program to open, read and write files using system calls.
2. Write a program to write line of texts in a file using system calls.
3. Write a program to open, read and write files and perform file copy operation.
Output :
Read and write:
Enter the source filename:
Deepi
Enter the destination filename:
Deepa

CS 2257 OPERATING SYSTEMS LAB

37

Ex.No:5
Date:
SIMULATION OF UNIX COMMANDS
Aim:
To simulate the following unix commands
1)ls
2)grep
Description
ls
Use ls to see what files you have. Your files are kept in something called a
directory.
% ls
foo
letter2
foobar letter3
letter1 maple-assignment1
%
Note that you have six files. There are some useful variants of the ls command:
% ls l*
letter1 letter2 letter3
%
Note what happened: all the files whose name begins with "l" are listed. The asterisk (*)
is the " wildcard" character. It matches any string.
grep
Use this command to search for information in a file or files. For example,
suppose that we have a file dict whose contents are
red rojo
green verde
blue azul
white blanco
black negro
Then we can look up items in our file like this;
% grep red dict
red rojo
% grep blanco dict
white blanco
% grep brown dict
%
Notice that no output was returned by grep brown. This is because "brown" is not in our
dictionary file.
Grep can also be combined with other commands. For example, if one had a file
of phone numbers named "ph", one entry per line, then the following command would
give an alphabetical list of all persons whose name contains the string "sona".
% grep sona ph | sort
sona College of technology salem-5
CS 2257 OPERATING SYSTEMS LAB

38

The symbol "|" is called "pipe." It pipes the output of the grep command into the input of
the sort command.

CS 2257 OPERATING SYSTEMS LAB

39

Exercises
1. Write a program for the simulation of ls command.
2. Write a program for the simulation for grep command.

Output:
Enter the directory name:
Rain
Violet
.
.
.
.
.

CS 2257 OPERATING SYSTEMS LAB

40

Ex.No: 6
Date:
CPU SCHEDULING ALGORITHMS -FCFS
Aim:
To implement FCFS (First Come First Served) scheduling algorithms.
Description
When a computer is multi programmed, it has multiple processes competing for
the CPU at the same time frequently. This situation occurs whenever two or more
processes are simultaneously in the ready state. If only one CPU is available, a choice has
to be made which process has to be in CPU. The part of the operating system that makes
the choice is called the scheduler and the algorithm is called scheduling algorithm.
FCFS
In this scheduling policy the processes are assigned the CPU according to the
order they arrive.
Algorithm:
1)
2)
3)
4)
5)
6)
7)

Start the program.


Declare the variables.
Get the number of process and their burst time for each process.
Draw the chart of the processes as first come first serve (FCFS) manner.
Calculate waiting time and turnaround time of each process.
Calculate average waiting and average turn around time of all the process.
Display waiting time, turnaround time, average waiting time and turn around
time of the processes.
8) Stop the program
Sample Input
Enter the number of processes:3
Process 1
Enter the CPU burst time: 5
Process 2
Enter the CPU burst time: 10
Process 3
Enter the CPU burst time:4

CS 2257 OPERATING SYSTEMS LAB

41

Sample Output:

Entet the no.of process:3


Enter the brust time:1
3
4
Enter the arrival time:0
0
0
Process
waiting time
P0
P1
P2

turnaround time

0
1
4

1
4
8

Avg.waiting time is 1.66667


Avg.turnaround time is 4.3333

CS 2257 OPERATING SYSTEMS LAB

42

CS 2257 OPERATING SYSTEMS LAB

43

Ex.No:7
Date:
CPU SCHEDULING ALGORITHMS SJF
Aim
To implement SJF (Shortest Job First) scheduling algorithms.
Description
When a computer is multi programmed, it has multiple processes competing for
the CPU at the same time frequently. This situation occurs whenever two or more
processes are simultaneously in the ready state. If only one CPU is available, a choice has
to be made which process has to be in CPU. The part of the operating system that makes
the choice is called the scheduler and the algorithm is called scheduling algorithm.
SJF
In this scheduling the process with shortest burst will be selected first. The
processes are sorted in ascending order according to the CPU burst time.
Algorithm:
1)
2)
3)
4)
5)
6)
7)
8)

Start the program.


Declare the variables.
Get the number of process and their burst time for each process.
Sort the processes in ascending order according to the burst time.
Draw the chart of the processes as in sorted order (SJF) manner.
Calculate waiting time and turnaround time of each process.
Calculate average waiting and average turn around time of all the process.
Display waiting time, turnaround time, average waiting time and turn around
time of the processes.
9) Stop the program
Sample Input
Enter the number of processes: 3
Process 1
Enter the CPU burst time: 5
Process 2
Enter the CPU burst time: 10
Process 3
Enter the CPU burst time:4

CS 2257 OPERATING SYSTEMS LAB

44

Sample Output

Enter the no.rocess:5


Enter the brust time:2
4
5
6
8
Process

waiting time

turnaroundtime

P[0]

P[1]

P[2]

11

P[3]

11

17

P[4]

17

25

Average waiying time = 17.2000


Avg turnarouondtime= 12.2

CS 2257 OPERATING SYSTEMS LAB

45

Ex.No:8
Date:
CPU SCHEDULING ALGORITHMS Priority scheduling
Aim
To implement using Priority scheduling algorithms.
Description
Priority
In this scheduling policy the processes are given certain priorities usually
specified as a number. They are sorted according to the priorities and the process with
highest priority is scheduled first.
Algorithm:
1)
2)
3)
4)
5)
6)
7)
8)

Start the program.


Declare the variables.
Get the number of process and their burst time and priority of each process.
Sort the processes in ascending order according to the priority of the process.
Draw the chart of the processes as in sorted order (priority) manner.
Calculate waiting time and turnaround time of each process.
Calculate average waiting and average turn around time of all the process.
Display waiting time, turnaround time, average waiting time and turn around
time of the processes.
9) Stop the program
Sample Input
Enter the number of processes: 3
Process 1
Enter the CPU burst time: 5
Enter the priority of the process : 2
Process 2
Enter the CPU burst time: 10
Enter the priority of the process : 3
Process 3
Enter the CPU burst time:4
Enter the priority of the process : 1

CS 2257 OPERATING SYSTEMS LAB

46

Sample Output

Enter the no.process:3


Enter the brust time(in ms)for process:#1:30
Enter the priority for process#1:2
Enter the brust time(in ms)for process:#2:20
Enter the priority for process#2:1
Enter the priority for process#3:3
Enter the brust time(in ms)for process:#3:40

Process
#2
#1
#3

startingtime
0
20
50

endingtime waiting time


20
50
90

0
20
50

turnarouond time
20
50
90

Avg:
Waiting time:23.33ms
Turnaround time;53.333

CS 2257 OPERATING SYSTEMS LAB

47

Ex.No:9
Date:
CPU SCHEDULING ALGORITHMS - Round Robin scheduling
Aim
To implement Round Robin scheduling algorithms.
Description
Round Robin
In this algorithm, a time quantum is fixed for the process to get executed in the
CPU. After that time quantum is over, the process is pre-empted and CPU is scheduled to
another process. This will continue until all processes in the system complete their turn.
Algorithm:
1)
2)
3)
4)
5)

Start the program.


Declare the variables.
Get the number of process and their burst time of each process.
Get the quantum time.
Schedule the CPU to the first process, after that quantum time is over schedule
the second process .. This will continue until all processes in the system
complete their turn.
6) Draw the chart of the processes as Round Robin manner.
7) Calculate waiting time and turnaround time of each process.
8) Calculate average waiting and average turn around time of all the process.
9) Display waiting time, turnaround time, average waiting time and turn around
time of the processes.
10) Stop the program
Sample Input
Enter the number of processes: 3
Process 1
Enter the CPU burst time: 5
Process 2
Enter the CPU burst time: 10
Process 3
Enter the CPU burst time: 4
Enter the quantum time: 3

CS 2257 OPERATING SYSTEMS LAB

48

Sample Output:
Enter the process :4
Enter the process name and brust time for the process
Enter the process :1
Enter the brust time for the process 1:8
Enter the process :2
Enter the process :3
Enter the brust time for the process 3:6
Enter the process :4
Enter the brust time for the process 4:1

Process name

brust time

1.roundrobin

2.exit

enter the time slice:


processname

remainingtime

totaltime

10

12

14

16

CS 2257 OPERATING SYSTEMS LAB

49

CS 2257 OPERATING SYSTEMS LAB

50

Ex.No:10
Date:
INTER PROCESS COMMUNICATION USING SHARED MEMORY
Aim:
To implement inter process communication using shared memory.
Algorithm:
1. Create the child process using fork().
2. Create the shared memory for parent process using shmget() system call.
3. Allow the parent process to write in shared memory using shmptr pointer
which is return type of shmat().
4. Attach the same shared memory to the child process.
5. The data in the shared memory is read by the child process using the shmptr.
6. Detach and rebase the shared memory.
Output :
Child is reading
ab cdefghij
parent is reading
ab cdefghij

CS 2257 OPERATING SYSTEMS LAB

51

Ex.No:11
Date:
INTER PROCESS COMMUNICATION USING PIPES
Aim:
To implement inter process communication using Pipes
Algorithm:
1. Create the child process using fork ().
2. Create the pipe structure using pipe ().
3. Close the read end of the parent process using close ().
4. Write the data in the pipe using write ().
5. Close the write end of child process using close ().
6. Read the data in the pipe using read ().
7. Display the string.
SAMPLE OUTPUT

Ex.No:12
Date:
PRODUCER- CONSUMER PROBLEM USING SEMAPHORES
CS 2257 OPERATING SYSTEMS LAB

52

Aim:
To implement Producer-Consumer Problem using semaphores.
Description
Whenever there are more than one processes running in the system, they may
have access same data. This problem is termed as Inter Process Communication. One
such problem is producer-consumer also called as bounded buffer problem. Two
processes share a common, fixed size buffer. The producer puts information into the
buffer and the consumer takes it out. Problem arises when the producer wants to put a
new item in the buffer but it is already full. Similarly if the consumer wants to take an
item but buffer is empty. This can be solved easily using semaphores.
An algorithm to Producer-Consumer problem with bounded buffer is shown
below:
Semaphore mutex=1 // binary semaphore that ensures that only one accesses the buffer
Semaphore empty=N // indicates the number of empty slots in the buffer
Semaphore full=0 // indicates the number of filled slots in the buffer
Producer()
{
while(true)
{
produce_item(item);
decrement(empty);
decrement(mutex);
enter_itme(item);
increment(full);
increment(mutex);
}
}
Consumer()
{
while(true)
{
decrement(full);
decrement(mutex);
remove_item(item);
increment(empty);
increment(mutex);
consume(item);
}
}

CS 2257 OPERATING SYSTEMS LAB

53

Algorithm:
1)
2)
3)
4)
5)
6)
7)
8)

Start the program.


Declare the required variables.
Initialize the buffer size and get maximum item you want to produce.
Get the option, which you want to do either producer, consumer or exit from the
operation.
If you select the producer, check the buffer size if it is full the producer should not
produce the item or otherwise produce the item and increase the value buffer size.
If you select the consumer, check the buffer size if it is empty the consumer
should not consume the item or otherwise consume the item and decrease the
value of buffer size.
If you select Exit come out of the program.
Stop the program.

Sample input:
Enter the maximum size of the buffer: 3
Enter your choice: producer, consumer or exit
Output:
Item produced
Item consumed..
Content of the buffer
Producer should not able produce..
Consumer should not able to consume

CS 2257 OPERATING SYSTEMS LAB

54

Ex.No:13
Date:
IMPLEMENTATION OF PAGE REPLACEMENT ALGORITHMS-FIFO
Aim:
To implement FIFO page replacement algorithm.
Description
FIFO
This is the simplest page replacement algorithm. A FIFO replacement algorithm
associates with each page the time when the page was brought into the memory. When
the page must be replaced, the oldest page is chosen. FIFO Page replacement algorithm
can be implemented using a FIFO queue. When a page is brought into the memory, we
insert it at the tail of the queue. We replace the page at the head of the queue.
Algorithm:
1)
2)
3)
4)
5)
6)
7)
8)

Start the program.


Declare the required variables.
Get the total number of frames and strings.
Check the page fault, if page fault occur replace the first added string.
Else no need to replace the page.
Count the number of page fault.
Print the number of page fault and content of the frame in each time.
Stop the program

Sample input:
Enter the no of frames:
Enter the no strings:
Enter the strings:
Output:
Content of frames:
Page fault occurred or not:
No of page faults:

CS 2257 OPERATING SYSTEMS LAB

55

Ex.No:14
Date:
IMPLEMENTATION OF PAGE REPLACEMENT ALGORITHMS-LRU
Aim:
To implement LRU page replacement algorithm.
Description
LRU
LRU uses the recent past as an approximation of near future. We replace the page
that has not been used for the longest period of time. Two implementations are feasible:
1. Counters:
In the simplest case, we associate with each page table entry a time-of use field,
and add to the CPU a logical clock or counter. The clock is incremented for every
memory reference. Whenever a reference to a page is made, the contents of the clock are
copied to the time-of use field in the page table entry for that page. We replace the page
with the smallest time value.
2. Stack:
Maintain a stack of page numbers. Whenever a page is referenced, it is removed
from the stack and put on top. In this way, the top of the stack is always the most recently
used page and the bottom is the LRU page. Because entries must be removed from the
middle of the stack, it is best implemented by a doubly linked list, with a head and tail
pointer.
Algorithm:
1)
2)
3)
4)
5)
6)
7)
8)

Start the program.


Declare the required variables.
Get the total number of frames and strings.
Check the page fault, if page fault occur replace string n LRU manner.
Else no need to replace the page.
Count the number of page fault.
Print the number of page fault and content of the frame in each time.
Stop the program

Sample input:
Enter the no of frames:
Enter the no strings:
Enter the strings:
Output:
Content of frames:
Page fault occurred or not:
No of page faults:
Ex.No:15
Date:
MEMORY MANAGEMENT SCHEMES - II
CS 2257 OPERATING SYSTEMS LAB

56

Aim:
To implement first fit, best fit and worst fit storage allocation algorithms 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.
Exercise
Write a program to simulate the above memory management scheme.

Ex.No:16
Date:
FILE ALLOCATION TECHNIQUES

CS 2257 OPERATING SYSTEMS LAB

57

File structure
-Logical storage unit
-Collection of related information
-File system resides on secondary storage (disks).
-File system organized into layers.
-File control block storage structure consisting of information about a file.
ALLOCATION METHODS:
An allocation method refers to how disk blocks are allocated for files:
Contiguous allocation
Linked allocation
Indexed allocation
Contiguous allocation

Each file occupies a set of contiguous blocks on the disk.


Simple only starting location (block #) and length (number of blocks) are
required.
Random access.
Wasteful of space (dynamic storage-allocation problem).
Files cannot grow.

Linked allocation

Each file is a linked list of disk blocks: blocks may be scattered anywhere on the
disk.

CS 2257 OPERATING SYSTEMS LAB

58

Simple need only starting address


Free-space management system no waste of space
No random access
Mapping

Indexed allocation

Brings all pointers together into the index block.


Logical view.
Need index table
Random access
Dynamic access without external fragmentation, but have overhead of index
block.

CS 2257 OPERATING SYSTEMS LAB

59

Aim:
To implement Contiguous File allocation techniques.
Algorithm:

Ex.No:17
Date:
CS 2257 OPERATING SYSTEMS LAB

60

DEADLOCK-BANKERS ALGORITHM
Aim:
To implement bankers algorithm for deadlock avoidance.

Algorithm:
1. Obtain the number of process from the user.
2. Get the allocation matrix , max matrix from the user for each process.
3. Find the need matrix for each process which is
Need[i][j]=max[i][j] - allocation[i][j]
4. Now, check for safe sequence using bankers algorithm.
5. If safe sequence exists, display it.
6. Else display no safe sequence.

Ex.No:18
Date:
CS 2257 OPERATING SYSTEMS LAB

61

DINING PHILOSOPHERS PROBLEM


Aim:
To implement dining philosophers problem for deadlock avoidance.
The Dining Philosophers problem is a classic OS problem thats usuallu stated in very
non-OS terms: There are N philosphers sitting around a circular table eating spaghetti and
discussing philosphy.
The problem is that each philosopher needs 2 forks to eat, and there are only N forks, one
between each 2 philosophers. Design an algorithm that the philosophers can follow that
insures that none starves as long as each philosopher eventually stops eating, and such
that themaximum number of philosophers can eat at once.
Why describe problems this way? Well, the analogous situations in computers are
sometimes so technical that they obscure creative thought. Thinking about philosophers
makes it easier to think abstractly. And many of the early students of this field were
theoreticians who like abstract problems. There are a bunch of named problems - Dining
Philosophers, Drinking Philiosophers, Byzantine Generals,etc.
Heres an approach to the Dining Phils1 thats simple and wrong:
void philosopher() {
while(1) {
sleep();
get_left_fork();
get_right_fork();
eat();
put_left_fork();
put_right_fork();
}
}
If every philosopher picks up the left fork at the same time, noone gets to eat - ever.
Some other suboptimal alternatives:
Pick up the left fork, if the right fork isnt available for a given time, put the left fork
down,
wait and try again. (Big problem if all philosophers wait the same time - we get the same
failure mode as before, but repeated.) Even if each philosopher waits a different random
time, an unlucky philosopher may starve (in the literal or technical sense).
Require all philosophers to acquire a binary semaphore before picking up any forks.
This guarantees that no philosopher starves (assuming that the semaphore is fair) but
limits parallelism dramatically. (FreeBSD has a similar problem with multiprocessor
performance).
Heres Tannenbaums example, that gets maximum concurrency:
1 Now that youve seen the problem, you can call them Phil, too.
-2#define N 5 /* Number of philosphers */
#define RIGHT(i) (((i)+1) %N)
CS 2257 OPERATING SYSTEMS LAB

62

#define LEFT(i) (((i)==N) ? 0 : (i)+1)


typedef enum { THINKING, HUNGRY, EATING } phil_state;
phil_state state[N];
semaphore mutex =1;
semaphore s[N]; /* one per philosopher, all 0 */
void test(int i) {
if ( state[i] == HUNGRY &&
state[LEFT(i)] != EATING &&
state[RIGHT(i)] != EATING ) {state[i] = EATING; V(s[i]);}
}
void get_forks(int i) {
P(mutex);
state[i] = HUNGRY;
test(i);
V(mutex);
P(s[i]);
}
void put_forks(int i) {
P(mutex);
state[i]= THINKING;
test(LEFT(i));
test(RIGHT(i));
V(mutex);
}
void philosopher(int process) {
while(1) {
think();
get_forks(process);
eat();
put_forks(process);
}
}
The magic is in the test routine. When a philosopher is hungry it uses test to try to eat. If
test fails, it wiats on a semaphore until some other process sets its state to EATING.
Whenever a philosopher puts down forks, it invokes test in its neighbors. (Note that test
does nothing if the process is not hungry, and that mutual exclusion prevents races.)
So this code is correct, but somewhat obscure. And more importantly, it doesnt
encapsulate the philosopher - philosophers manipulate the state of their neighbors
directly. Heres a version that does not require a process to write another processs state,
and gets equivalent parallelism.
-3#define N 5 /* Number of philosphers */
#define RIGHT(i) (((i)+1) %N)
#define LEFT(i) (((i)==N) ? 0 : (i)+1)
typedef enum { THINKING, HUNGRY, EATING } phil_state;
phil_state state[N];
semaphore mutex =1;
semaphore s[N]; /* one per philosopher, all 0 */
void get_forks(int i) {
state[i] = HUNGRY;
CS 2257 OPERATING SYSTEMS LAB

63

while ( state[i] == HUNGRY ) {


P(mutex);
if ( state[i] == HUNGRY &&
state[LEFT] != EATING &&
state[RIGHT(i)] != EATING ) {
state[i] = EATING;
V(s[i]);
}
V(mutex);
P(s[i]);
}
}
void put_forks(int i) {
P(mutex);
state[i]= THINKING;
if ( state[LEFT(i)] == HUNGRY ) V(s[LEFT(i)]);
if ( state[RIGHT(i)] == HUNGRY) V(s[RIGHT(i)]);
V(mutex);
}
void philosopher(int process) {
while(1) {
think();
get_forks(process);
eat();
put_forks();
}
}
If you really dont want to touch other processes state at all, you can always do the V to
the left and right when a philosopher puts down the forks. (Theres a case where a
condition variable is a nice interface.) Tannenbaum discusses a couple of others that are
worth looking at.
Deadlock
Another danger of concurrent programming is deadlock. A race condition is produces
incorrect results, where a deadlock results in the deadlocked processes never making any
progress. In the simplest form its a process waiting for a resource held by a second
process thats waiting for a resource that the first holds.
4 Conditions
More formally there are 4 conditions for deadlock:
Mutual Exclusion: Resources can only be held by at most one process. A process
canniot
deadlock on a sharable resource.2
Hold and Wait: A process can hold a resource and block waiting for another.
No Preemption: The operating system cannot take a resource back from a process that
has it.
Circular Wait: A process is waiting for a resource that another process has which is
waiting for a resource that the first has. This generalizes.

CS 2257 OPERATING SYSTEMS LAB

64

If these 4 conditions are necessary and sufficient. (If these four appear, there is a
deadlock, if not no deadlock.) The problem is that the chain in a circular wait can be long
and complex.
Reactions To Deadlock
An OS can react to deadlock one of 4 ways:
Ignore it
Detect and Recover from it
Avoid it (invest effort at run-time to make deadlock impossible)
Prevent it (short circuit one of the 4 conditions )
Ignoring Deadlock
Running, stable Operating Systems ignore potential deadlocks. In fact, I would venture
that there is no production operating system that cannot be deadlocked by pathological
behavior.

CS 2257 OPERATING SYSTEMS LAB

65

You might also like