0% found this document useful (0 votes)
6 views

Updated OS Lab11

Uploaded by

rishav ray
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Updated OS Lab11

Uploaded by

rishav ray
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 95

ALLIANCE COLLEGE OF ENGINERING AND DESIGN

DEPARTMENT OF COMPUTER SCIENCE AND TECHNOLOGY

OPERATING SYSTEM LABORATORY MANUAL


CSL 507

V SEMESTER
Batch: 2019-2023

Prepared by

Dr. Abraham George


Professor & Head of Department
Computer Science & Engineering

This is to Certify that_______________ Registration Number____________of the


V-Semester, Computer Science and Engineering has completed the CSL507-
Operating Systems Lab.

_______________ _________________
Faculty Signature Head of Department

OS-CSL507 1
Vision:

To Empower the undergraduate and postgraduate emphasis on create conductive


environment for quality academic and research-oriented education in computer science
and engineering and formulate the students to contribute significantly towards globalised
technology and serving the society.

Mission:
• To impart Excellence high quality professional training at the postgraduate
and undergraduate level with an emphasis on pedagogies and hands on
experience on recent tools and technologies.
• To establish internationally recognized research centres and expose the
students in interdisciplinary research to serve up global community.
• Prepare students for acquiring professional skills and ethical responsibilities
in them.
• To Reinforce the industry-academia interface that stipulate graduates to
emerge as leaders and revolutionary entrepreneur.

PEO 1: To provide graduating students with core competencies and continued learning
with critical thinking to solve humanity and societal problems
PEO 2: To enable the student to provide dynamic solution to real time problems, design
Thinking enable them to work in a multi-disciplinary with strong focus on the core
technical knowledge and key management skills.
PEO 3: To enable students to work on the cutting-edge technology and understand the
computational complex domains.

Program Outcome:
Graduates will have the ability to
1. Apply the knowledge of mathematics, basic science, engineering fundamentals to
solve problems related to computer science and engineering.
2. Identify, formulate, design, and analyse solution for complex problem to solve societal
needs.
3. Analyse complex scenarios and implement computational intelligence for deriving
solutions.
4. Implement mathematical models and solutions to the research problems applicable in
all aspects of life
5. Create, select, and apply suitable techniques, resources, and modern engineering and
IT tools for complex engineering activities

6. Apply reasoning informed by the contextual knowledge to assess societal, health,


safety, legal and cultural issues and provide effective IT solutions through software
engineering practices.

7. Understand the impact of the professional engineering solutions of Computer Science


and Engineering in societal and environmental contexts and provide solution.

OS-CSL507 2
8. Apply ethical principles and commit to professional ethics and responsibilities towards
working environment

9. Function effectively as an individual, and as a member or leader in diverse teams, and


in multidisciplinary settings

10. Communicate effectively on computer engineering activities with the engineering


community and with the diverse society through reports, documentation and
presentations.

11. Demonstrate the knowledge and understanding of software engineering and


management principles and apply them as a member and leader in a team, to
implement and manage projects.

12. Recognize the need for continued learning as individual and serve the society .

OS-CSL507 3
SYLLABUS FOR OS LAB

Course
Course Title Core/Elective
Code

Operating
CSL507 Core
Systems Lab

List of experiments:

1. Familiarity and usage of Linux System calls :


a. Process management: fork(), exec(), wait(), sleep() ...,
b. File management: open (), read (), write (), seek (), close ()...,

2. Write a program to Implement two process communication using


IPC constructs. a) pipes b) shared memory
c) message queues d)Semaphores..

3. Demonstrate the use of threads under LINUX platform using appropriate


thread API

4. Write a program to Implement Producer Consumer Problem solution.

5. Write a program to Implement Dining philosopher’s problem solution.

6. write a program to implement Processor Scheduling Algorithms


a) FCFS b) SJF c) Round Robin.
7. Write a program to simulate Bankers Algorithm for Dead Lock Avoidance.

8. Write a program to Implement Page replacement Algorithms:


a) FIFO b) LRU
9. Write a program to implement disk scheduling algorithms.
a) FCFS b) SCAN c) C-SCAN

LIST OF EXPERIMENTS
OS-CSL507 4
SERIAL
CONTENTS PAGE NO
NO
I INTRODUCTION
a)Operating system 6
b)Commands 14
II PROGRAMS
Process Management
a) fork()
b) execv()
1 c)execlp() 26
d)wait()
e)sleep()
Process Synchronization
a)pipe
2 b)semaphore id 38
c) shared memory id
d) file read and write
Demonstrate the use of threads under LINUX
3 platform using appropriate thread API 49
Write a program to Implement Producer
4 55
Consumer Problem solution
Write a program to Implement Dining
5 philosopher’s problem solution. 65
write a program to implement Processor
6 Scheduling Algorithms a) FCFS b) SJF 70
Write a program to simulate Bankers Algorithm
7 for Dead Lock Avoidance. 78
Write a program to Implement Page
8 replacement Algorithms: 82
a) FIFO b) LRU
Write a program to implement disk scheduling
9 90
algorithms. a) FCFS b) SCAN

INTRODUCTION
OS-CSL507 5
OPERATING SYSTEM :-
A program that act as an intermediary between a user of a computer and
the computer hardware.

An operating system can be define as a software that control the


hardware resources of the computer and provide an environment under
which program can run. Generally, we call this software as the KERNEL.

OPERATING SYSTEM GOALS :-

Execute user programs and make solving user problem easier.

Make the computer system convenient to use.


Operating system is a software program that enables the
computer hardware to communicate & operate with the
computer software.

Without operating system a computer would be useless.

COMPUTER SYSTEM COMPONENTS :

A computer system can be divided roughly into four components; the


hardware, the operating system, the application program and the user.

Hardware :
Provide basic computing resources (CPU, memory, Input/output
devices).

Operating System :
Control & coordinates the use of the hardware among the
various application program for the various users.

Application Program :

OS-CSL507 6
Define the way in which the system resources are used to solve
the computing problems of the user (compiler, database system, video
games, business program).

Users :
(People, machines, other computers).

VIEW OF SYSTEM COMPONENTS :-

USER USER USER USER

1 2 3 n

COMPILER ASSEMBLER TEXT EDITOR ------------ DATABASE


SYSTEM

(SYSTEM AND APPLICATION PROGRAMS)

OPERATING SYSTEM
COMPUTER
HARDWARE

OS-CSL507 7
PROCESS :-

A process is a program in execution. The components of a process are.


The program to be executed.
The data on which the program will execute.
The resource required by the program – such memory and files.
The status of the execution.

PROGRAM :-
It is an executable file.
It is usually created by link editor and recites on disk files.

SYSTEM CALL :-

I/F to the kernel is a large of software called the System Calls.

Libraries of common function are built on top of the system call I/F,but
application are free to use both
Shell is a special application that provides on I/F for running other
application.

OS-CSL507 8
All OS provides service points through which program request services from
the kernel.all implementation of the UNIX system provides a well-
defined,limited no.of entry point directly into the kernel called SYSTEM
CALLS.

A kernel provides a limited number of direct entry points(i.e a table) through


which an active process can obtain service from the kernel pid==0.Any
system call(pid,fork,wait) returns -1 if an error occur or a value greater
than or equal to 0 if all is ok.

PROCESS :-
An executing instance of a program is called a process. Most of the
operating system identifies processes according to unique process identifier (i.e.,
pid). Which is typically a integer number.

Every process has a unique process id. It is an integer


that ranges from (0 to 30,000).
Kernel assigns the pid when a new process is created and process can obtain
its pid.
• Process id 1 – it is a special kernel process use init.
• Process id 2 – it is used for scheduler(C P U ).
• Process id 3 – it is used for page demo.

GETPID () :-
It enables us to get the identification number of a process

Example :
main ()
{
int pid;
pid = getpid ();
printf(“\n process id %d\n”,pid);

Pid value will depend on the number of process already running it will always
be unique.

OS-CSL507 9
GETPPID () :-
It will give the id number of its parent. In the case of parent when we boot the
system a special process called swapper or scheduler is created with a pid of o.
the swapper manages memory allocation for process and influence CPU
allocation. The swapper in turn create 3 children the process dispatcher, vhand,
bd flush with id number 1,2 & 3.

TELNET :-
The telnet command is used to communicate with another host using the telnet
protocol. Where hostname is the host you want to connect to & port, indicates a
port number. If a number is not specified, the default telnet is used.

Example:

Operating System Server Internet Protocol


Linux Telnet 192.168.0.5
Unix Telnet 192.168.0.2

UNIX:-
An operating system developed in olden days in which kernel interacts
directly with the hardware. Kernel is considered to be the hard of the
operating system.

In this operating system everything is considered as a file, provides greater


facility.

Example:

POSIX
LINUX:-

Linux is operating systems which use UNIX as its base and gives
further more facilities and applications.
Merely speaking GUI is made in Linux having UNIX as its core.
Example:

Red Hat, Fedora, Mandrake.

OS-CSL507 10
Solaris operating system also using the same UNIX kernel all the UNIX
commands will work on Solaris & have 500 more Solaris specific
commands. Different organization used the UNIX kernel and added their
own essence to from their own version of Linux.

UNIX is portable: it can be a mainframe all the way to a cheap


wintelceron-design machine that you picked up at walmast for under rupees
$200.

LINUX is built upon UNIX. UNIX alone doesn’t have a GUI, & the kernel is
not a developer.
The single largest difference between LINUX and a modern UNIX system is
that LINUX & a modern UNIX system is that LINUX is free & open source.
UNIX is a multiuser, timesharing; multitasking operating system
developed a group of AT & t employees including Dennis Ritchie & ken
Thompson, both of them who were regarded as being the biggest
contributors to both UNIX & the programming language “c”. UNIX itself
traces back to be influenced by multics.
Linux is an operating system which is UNIX like. In a sense, they have the
same operating system interface to which application programs can be
built on. They strictly confirm to the single UNIX specification & POSIX
(post operating system interface). The interface is similar to the UNIX
machinery but the implementation is to specific contributors of the Linux
community along with LINUX torvalds.
Intuitively, UNIX which being an operating system over the time has
evolved into a operating system specification & LINUX is a specific Unix
implementation.

UNIX FILES SYSTEM :


The UNIX file system resembles an upside down tree. Thus, the

OS-CSL507 11
file system begins with a directory called root. The root directory is denoted
as slash (/). Branching from the root there are several other directory called
bin, lib, user, etc and dev. The root directory also contains a file called UNIX
which is UNIX kernel itself.

BASIC STRUCTURE OF THE UNIX FILES SYSTM:-

ROOT

UNIX dev usr tmp etc


bin lib

User User User bin


1 2 3

OS-CSL507 12
DIRECTORY CONTAINS
Bin Binary executable files
Lib Library functions
Dev Device related files
Binary executable files usually
Etc
required for system administration.
Temporary files created by unix or
Tmp
user
Usr Home directories of al users
/usr/bin Additional binary executable files

File type Meaning


- Ordinary file
D Directory File
C Character Special File
D Block Special File
L Symbolic Link
S Semaphore
P Name Pipe
M Shared Memory File

OS-CSL507 13
COMMANDS

1. Copy :-
Syntax :

cp SourceFileName.c DestinatioFileName.c

Purpose :
Copies a file or graph of files.
Description :
When both are ordinary files, the first is copied into second. If
destination file doesn’t exit, it will be created before copying takes
places. If it does exit, it will simply be overwritten without any warning
from the system.
Example :
$cp letter.a letter.b
• This will copy the contains of letter.a into the file letter.b.

$cp letter.a letter.b letter


• All files mentioned are copied into the directory called
LETTER, provided that directory must exit.

Parameters Used by Copy :

Options Use
Creates a link file instead of
-l
copying.
Dereference always follow Symbolic
-L
links.
-r Copy recursively.
-R Copy directory recursively.
Update, copy only when source file
-u is newer than destination file or
destination not found.

Example :
$cp -r letter.a letter.b
OS-CSL507 14
2. Move :-
Syntax :
mv[options] Source Destination

mv FileName1 FileName2
mv DirectoryName1 DirectoryName2
mv FileName DirectoryName

Purpose :
Rename Files and Directories.

Description :
When both are ordinary files, the first is moved into second. If
destination file doesn’t exit, it will be created before copying takes
place. If it does exit, it will simply be overwritten without any
warning from the system.

$mv FileName1 FileName2

Example:

➢$mv OldDirectoryName NewDirectoryName

➢ On execution of this command FileName1 no longer exit


at its original location, but the contents of FileName1 is
moved to FileName2.
➢ OlddirectoryName will be renamed to NewDirectoryName
,provided
NewDirectoryName is not existing already.

Note: Options used in move command will be same as used in


copy command.

3. Remove :-
OS-CSL507 15
Syntax:

rm [Option] SourceFileName
rm [Option] Source1 Source2

(Remove Source1 and Source2 Files)

Purpose: Remove File

4. Mkdir:-
Syntax :

mkdir DirectoryName

$rm File1 File2 File3

Purpose :
The function creates new empty directory.

Description :
Directory is created with this command. The command is
followed by names of the directories to be created. It takes
multiple arguments so; number of subdirectories can be created
with a single command. The entries with”-“and “- -“automatically
created. When a file created it be read and write permission. For
creating a file, a user must have write permission for directory.

OS-CSL507 16
5. Mkdir:-
Syntax :

mkdir DirectoryName

$rm File1 File2 File3

Purpose :
The function creates new empty directory.

Description :
Directory is created with this command. The command is
followed by names of the directories to be created. It takes
multiple arguments so; number of
subdirectories can be created with a single command. The entries
with”-“and “- -“automatically created. When a file created it be
read and write permission. For creating a file, a user must have
write permission for directory.

Example:

mk dir Directory1 Directory2 Directory3


• Create 3 subdirectories (i.e. Directroy1, Directroy2, and


Directroy3) in current directories.

Note: User Should have write permissions on the current directory


to create a new directory.

6. Rmdir :-
OS-CSL507 17
Syntax:

Rmdir [Option] DirectoryName

Purpose :
Removes empty directories.

Description :
Directories are removed with this command. The command can
delete more than a single directory at one time. This command
removes an empty directory. A subdirectory cannot be removed
unless it is placed in a directory that is huracchical above the one
that is chosen to remove.

Example:
rmdir Directory1 Directory2 Directory3
• Remove 3 directories (i.e. Directory1, Directory2 and Directory3).
• To remove the directory book.

$rmdir works/bpb/unix/book

• Removing the book directory if the UNIX directory falls empty


then it is removed. On removing the UNIX directory if the bpb
directory falls empty then that too get removed and so on. This
process stops when rmdir bumps into a non-empty parent
directory.

$rmdir -p works/bpb/unix/book
• With the –p option, rmdir wields enough power to remove not
only the specified directory, but also its parent directories.

OS-CSL507 18
7. Cd :-

Syntax:
cd DirectoryName

Purpose :
Changing over to a new directory.

Description:
Cd when given without any argument is interpreted by the shell
as a request to change over to the current user’s home directory. A cd
will bring you back where you belong to your home directory.

Example :

$mkdir NewDirectory

$cd NewDirectory

• This would take you in NewDirectory.


• If you try to move to directory that doesn’t exist or if you incorrectly
type the directory name or path name, UNIX reports an error.

OS-CSL507 19
Vi – Visual Editor :-
The Vi program has three following modes of operation

1. Command mode:
In this mode all the keys pressed by the user are interpreted
to be editor commands.

If you hit ‘h’ the cursor is moved one position to the


left. In command mode the keys that are hit are not
displayed on the screen.

2. Insert Mode :
This mode permits insertion of new text, editing of existing text on
replacement of existing text. Each of these operation can be
performed only after changing over from the command mode to
insertion mode using appropriate command the insertion mode is
also known as input –text mode.

3. Ex command mode :
This mode permits us to give command at the command line. The
bottom line of the Vi screen is called the command line.vi uses the
command line to display messages and commands. All commands
entered in the ex command mode are displayed in the command
line. This mode is so called because commands given in this mode
are compatible with the commands of the ex editor.

OS-CSL507 20
COMMANDS FOR INSERTING TEXT :

Command Function
Enter text I/P mode and insert
i
mode.
a Append to right mode.
Enter text I/P mode and
A append text at the end of
current line.
Enter text I/P mode and
I insert text at the beginning of
current line.
Enter text I/P mode by opening
a new
o
line immediately below the
current line.
Enter text I/P mode by
opening a new line
O
immediately above the current
line.
Enter text I/P mode and
overwrites
R
from current cursor
position on wards.

COMMAND FOR DELETING TEXT:

Command Function
Deletes the character at
^
current cursor position.
Deletes the character to the
X
left of the cursor.
Deletes a word from the
current to the next space or
dw
to the next
punctuation.
dd Deletes the current line.
Deletes n character words or n
nx, ndw, ndd
lines.
OS-CSL507 21
Deletes the current line
do from the cursor to the
beginning of the line.
Deletes the current line
d$ from the cursor to the end
of the line.

OS-CSL507 22
MISCELLANEOUS COMMANDS:
Command Function
Gives the line no. Of current
cursor position in the buffer
Ctrl +g
and
modification status of the file.
Repeats the action performed
.
by the last command.
Undoes the effects of
u
the last command.
Restores all changes to the
current
U
line since you moved the
cursor to this line.
Joins the line immediately
J below the current line with
the current line.
Temporarily returns to the
shell to perform some shell
:sh
commands. Type exit to
return to vi.
Clears and redraws the
Ctrl +l
current window.

COMMANDS FOR QUITTING VI:


Note:-put command line entry(i.e. : ) at the foot of the screen.

Command Function
zz or :wq Save and quit.
:q! Quit without saving
:qa Quit all files opened.
Quit vi if changes made to
:q the buffer were written to a
file.
Write the buffer to the file
:w filename & :q
filename (new) quit vi.
Overwrites the existing the file
filename with the
:w! filename & :q
contents of the buffer and
quits vi.
OS-CSL507 23
:wcr Writes back changes.

COMPILE AND EXECUTION COMMAND :-

Compilation command :

cc Filename.c

Where,
cc is the c-compiler.

Filename is the file name with .c data type.

Execution Command:

./a.out

This is a file format used in UNIX for executables, objects codes. The
name stands for assembler O/P.

a.out remains the default O/P file name for executables created by the
compiler when no O/P name is specified ,even though the executables
are no longer in the a.out form.

OS-CSL507 24
PROCESS RELATED SYSTEM CALLS:-

Fork ( ):
The fork () system call creates a new process called a child. The
original process is called the parent, and the child is a near-exact copy of the
parent. The child’s runtime is set to zero, whereas for the parent it returns the
PID of child. The child has its own process ID and its own copy of the parent’s
file descriptors.

Syntax:

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

Sleep ( ):-
A process that voluntarily blocks for a specified time is said to
sleep. The sleep function causes the calling thread to be suspended either until
the specified number of seconds has elapsed or the specified number of seconds
has elapsed on until the calling thread catches a signal.

A typical sleep system call takes a time value as a parameter,


specifying the minimum amount of time that the process is to sleep
before resuming execution.
Sleep function returns zero, if the requested time has elapsed or the
amount of UN slept time if interrupted.
In sleep system call, the parameter are used are typically specifies
seconds, although some operating system provide finer resolution, such
as milliseconds or microseconds.

OS-CSL507 25
Wait ( ):
An operating system may provide variations of the wait call that allow a
process to wait for any of its children process to exit and suspend the
parent process with a wait () function.
The parameter passed to the wait () function is a pointer to an integer. The
call to the wait () function result in the following things:
o Check is made to see if the parent process has any children if it
does not,-1 is returned by wait ().
o If the parent process has a child that has terminated that child
PID is return & it is removed from the process table.
o If the parent process has child/children that have not
terminated, it is suspended till it receives a signal. The signal is
received as soon as child dies.
A process can wait for its child process to finish by executing the wait system
call.

Syntax:

int wait (int *status);

The value returned by wait is the process id of the child process that
terminated. If the process that calls wait does not have any child process,
wait returns a value of -1 immediately.
If the process that calls wait has one or more child process that has not
yet terminated, than the calling process is suspended by kernel until one
of its child process terminated.
When a child process terminates & waits returns, if the status argument
is not NULL, the value passed to exit by the terminating child process is
stored in status variable. Some additional information is also returned by
wait.
There are three conditions for which wait returns a process id as its return
value.
o A child process called exit.
o A child process was terminated by a signal.
o A child process was being traced & the process s tracing the

OS-CSL507 26
execution of another process, such as when a debugger is being used
to step through a process.

Exec ( ) :
• The exec family of function provides a facility for overlaying the process
image of the calling with a new image.
• The various exec*() functions take a list of arguments for the new
program loaded into the process. In each case, the first of these
arguments is passed to the new program s its own name rather than as
an argument a user may have typed on a command line.

Execl(path, arg(), argl, …….)

Execle(path, arg(), argl,….,env)

Execlp(file, arg(), argl,…)

Execlpe(file, arg(), argl, ….,env)

Execv(path, args)

Execve(path, args, env)

Execvp(file, args)

Execvpe(file, args, env)

The “l” and “v” variants of the exec*( ) functions differ in how command-
line arguments are passed. The”l” variants are prepays the easiest to
work with if the number of parameters is fixed when the code is written;
the individual parameter simply become additional parameters to the
execl*() functions

OS-CSL507 27
The “v” variants are good when the number of parameters is variable, with
the arguments being passed in a list as the args parameter. In either case,
the argument to the child process should start with the name of the
command being run, but this is not enforced. The variants which include
a “p” near the end (execlp (), execlpe (), execup () and execupe ()) will use
the PATH environment variable to locate the program file. When the
environment is being replaced (using one of the exec*e() variants), the new
environment is used as the source of the PATH variable. The other variants, execl
(), execv (),execle (), and execve (), will not use the PATH variable to locate the
executable; path must contain an appropriate absolute or relative path. For execle
(), execlpe (), execve (), and execupe (), the env parameter must be a mapping
which is used to define the environment variables for the new process; the execl
(), execlp (), execv (), and execup () all cause the new process to inherit the
environment of the current process.
The exec () function will initiate a program from within a program. The
function return an integer error code (0 = ok, -1 = fail).

➢ Execl ( ) and execlp ():


• The function call “execl ()” initiate a new program in the same environment
in which it is operating. An executable (with fully qualified path i.e.,
/bin/ls) and arguments are passed to the function.
• The routine execlp () will perform the same purpose except that it will use
environment variable PATH to determine which executable to process.
Thus a fully qualified path name would not have to be use. The first
argument to the function could instead be “ls”. The function execlp () can
also resolves explicitly.

➢ Execv () and execup ():


• This is the same as execl () except that the argument are passed as NULL
terminated array of pointer to char. The first element argv [0] is the
command name.
• The routine execup () will perform same as “routine execlp ()”.

➢ Execue () :
OS-CSL507 28
• It executes a process in an environment which it assigns.

➢ Return value for Exec function :


If any of the exec () function returns an error will have occurred. The
return value is -1, & the global variable err no will be set to indicate the
error.

#include<unistd.h>
int execl (const char *path, const char *arg(), …/, char *const);
int execle (const char *path, const char *arg(), …/*, char *const enup[] */);
int execlp (const char *file, const char *arg(), …char);
int execv (const char *path, char *const argv[]);
int execve (const char *path, char const *argv [],char *const enup []);
int execup (const char *file, char *const argv []);

➢ In Exec () function:
It works when number of
l parameters is fixed when the
code is written.
When number of
v
parameters is variables.
e Environment variables.
h Path name.

OS-CSL507 29
PROGRAM TO IMPLEMENT THE FORK FUNCTION

#include<stdio.h>
#include<sys/type
s.h> main()
{
int pid;
pid=fork(
);
if(pid==0
)
{
printf("\n I am the child");
printf("\n I am the parent
:%d",getppid()); printf("\n I am the
} child :%d",getpid());
els
e
{
printf("\n I am the parent ");
printf("\n I am the parents parent
:%d",getppid()); printf("\n I am the
} parent :%d\n",getpid());
}

OUTPUT:

cc frk.c
./a.out

I am the child
I am the parent:
3944 I am the
child: 3945
I am the parent
I am the parents parent:
3211 I am the parent:
3944

OS-CSL507 30
PROGRAM TO IMPLEMENT EXECV FUNCTION

#include<stdio.
h>
#include<unist
d.h> main()
{
char
*temp[3];
temp[0]="ls"
;
temp[1]="-l";
temp[2]=(char *)0;
execv("/bin/ls",te
mp);
printf("this will not print\n");
}

OUTPUT:

cc
execv.c
./a.out
total 76
-rwxr-xr- 1 grou 4716 Mar 7 a.out
x be322 p 10:13
-rw-r--r- 1 be322 group 688 Feb 20 comm.c
- 13:52
-rw-r--r- 1 be322 group 925 Feb 20 echomsg.c
- 13:54
-rw-r--r- 1 be322 group 722 Feb 20 echopipe.c
- 13:55
-rw-r--r- 1 be322 group 178 Feb 20 exel.c
- 13:57
-rw-r--r- 1 be322 group 167 Mar 7 exev.c
- 10:13
-rw-r--r- 1 be322 group 1109 Feb 20 fflag.c
- 13:57
-rw-r--r- 1 be322 group 341 Dec 26 frk.c
- 14:47
-rw-r--r- 1 be322 group 140 Feb 20 linearg.c
- 13:57
-rw-r--r- 1 be322 group 528 Feb 20 lock.c
- 13:57
-rw-r--r- 1 be322 group 254 Feb 20 msg.c
- 13:57
-rw-r--r- 1 be322 group 1036 Feb 20 msgpass.c
OS-CSL507 31
- 13:57
-rw-r--r- 1 be322 group 203 Feb 20 sem.c
- 13:58
-rw-r--r- 1 be322 group 1167 Feb 20 sharememor
- 13:58 y.c
-rw-r--r- 1 be322 group 312 Feb 20 slp.c
- 13:58
-rw-r--r- 1 be322 group 1182 Feb 20 threadf.c
- 13:58
-rw-r--r- 1 be322 group 287 Feb 20 wt.c
- 13:59

OS-CSL507 32
PROGRAM TO IMPLEMENT EXECLP FUNCTION

#include<stdio.h>
#include<sys/type
s.h> main()
{
int pid;
pid=fork(
);
if(pid==0
)
{
printf("\n fork program
started");
} execlp("/bin/ls","ls",NULL)
els ;
e
{

} printf("\nend");
}

OUTPUT:

cc exel.c
./a.out

end$
fork program started
a.out comm.c
echomsg
.c
echopipe
.c exel.c
exev.c
fflag.c
frk.c
linearg.c
lock.c
msg.c
msgpass
.c sem.c
sharememor
y.c slp.c
threadf
.c wt.c

OS-CSL507 33
PROGRAM TO IMPLEMENT WAIT FUNCTION

#include<unist
d.h>
#include<stdio.
h> main()
{
int
i=0,pid;
pid=fork(
);
if(pid==0
)
{
printf("child process
started\n");
for(i=0;i<10;i++)
printf("\n%d",i);
} printf("\n child process ends");
els
e
{
printf("\n parent process
starts"); wait(0);
printf("\n parent process ends");
}
}

OUTPUT:

cc wt.c
./a.out

parent process
starts child
process started

0
1
2
3
4
5
6
7
8
9

OS-CSL507 34
child process
ends parent
process ends

OS-CSL507 35
PROGRAM TO IMPLEMENT SLEEP FUNCTION
#include<unist
d.h>
#include<stdio.
h> main()
{
int i=0,pid;
printf("\n ready for
fork\n"); pid=fork();
if(pid==0)
{
printf("\n child process
started \n"); sleep(4);
for(i=0;i<10;i++)
printf("\n%d"
,i);
} printf("\n child process ends");
els
e
{
printf("\n I am the
parent"); printf("\n parent
} process ends");
}

OUTPUT:

cc slp.c
./a.out

ready for
fork I am
the parent
parent process
ends child
process started

0
1
2
3
4
5
6
7
8
9
child process ends

OS-CSL507 36
PROCESS SYNCHRONIZATION:-
Synchronization means the coordination of simultaneous threads or
processes to complete a task in order to get correct runtime order and avoid
unexpected race conditions.

Inter-process communication (IPC) is a set of techniques for


the exchange of data among multiple threads in one or more processes.
Processes may be running on one or more computers connected by a
network. IPC techniques are divided into methods for message passing,
synchronization, shared memory, and remote procedure calls (RPC).

There are many types of synchronization:

* barrier

* lock/semaphore

* non-blocking synchronization

* synchronous communication operations

File Management(read, write)


#include<fcntl.h> - File control.
#include<stdlib.h> Standard library.

int open (const char *pathname,int aflag,……/*mode_t mode*/);

The pathname is the name of the file to open or create.

<fcntl.h>
This header file contains:
O_RDONLY --- open for reading only.
O_WRONLY - open for writing only.
O_RDWR ----- open for reading and writing.
O_APPEND -- append to the end of the file on each write.
O_RDWR ----- open for reading and writing.

OS-CSL507 37
O_CREATE -- create the file if it doesn’t exit. This option requires a third
argument to
the open function, which specifies the access permission
bit of the new file.

There are nine permissions bit for each file, divided into three categories as
shown below:

St_mode mask Meaning

S_IRUSR User –read

S_IWUS User –

R write User

S_IXUS –execute

R
S_IRGRP Group –read

S_IWGR Group –

P write Group

S_IXGR –execute

P
S_IROT Other –

H read

S_IWOT Other –

H write

S_IXOTH Other –
execute

Fig: Nine file access permission bits from <sys/stat.h>.

OS-CSL507 38
Here, in file locking program:

fd=open(“test”,0_APPEND|0_RDWR|0_CREAT,0660);
A better way is to use the open function, as in

open(pathname,0_RDWR|0_CREAT,mode);

Write():-
size_t write(int filedes,const void *buf,size_t nbytes);

Return value:
1. No. of bytes written if ok.
2. -1 written than error.

The return value is usually equal to nbytes argument; otherwise, an error has
occurred.

write(fd,”A”,1);

For a regular file, the write start at the file current offset. If the 0_APPEND option
was specified when the file was opend, the files offsetis set to the current end of
the file before each write operation. After a successful write, the files offset is
incremented by the no. of bytes actually written.

LOCK FUNCTION :-

This function allowed callers to lock arbitrary byte ranges in a file, from the
entire file down to a single byte within the file

• F_lock --- structure of lock.

OS-CSL507 39
Message Queues

Shared Memory

OS-CSL507 40
Semaphore
Semaphore Definition:-

▪ P (semaphore variable) for wait,


▪ V (semaphore variable) for signal.

A Mutex is a binary semaphore, usually including extra features


like ownership or priority inversion protection. The differences between
mutexes and semaphores are operating system dependent. Mutexes are meant
to be used for mutual exclusion only and binary semaphores are meant to be
used for event notification and mutual exclusion.

OS-CSL507 41
CREATING A PROGRAM FOR PIPE
#include<stdio.h>
#include<unistd.h
>
#include<sys/ipc.
h>
#include<sys/type
s.h> #define
msgsize 16 main()
{
char *msg="hello
world"; char
inbuff[msgsize];
int
p[2],pid,j;
pipe(p);
pid=fork();
if(pid>0)
{
close(p[0]);
write(p[1],msg,msgsize)
;
}
if(pid==0)
{
close(p[1]);
read(p[0],inbuff,msgsiz
e); printf("%s
\n",inbuff);
}}
OS-CSL507 42
OUTPUT
cc pipes.c
./a.out hello world

OS-CSL507 43
CREATING A SEMAPHORE ID

#include<unistd

.h>

#include<sys/ip

c.h> main()

int semid,key,nsem,flag;

key=(key_t)0X200f;

flag=IPC_CREAT|0666;

nsem=1;

semid=semget(key,nsem,fl

ag);

printf("Created a semaphore with id: %d \n",semid);

OUTPUT

Created a semaphore with id: 589832

OS-CSL507 44
CREATING A SHARED MEMORY ID

#include<sys/type

s.h>

#include<sys/ipc.

h>

#include<sys/sh

m.h> main()

int shmid,flag;

key_t

key=0X1000;

shmid=shmget(key,10,IPC_CREAT|066

6); if(shmid<0)

perror("shmid

failed"); exit(1);

printf("Success shmid is %d /n",shmid);

OUTPUT

Success shmid is: 682340

OS-CSL507 45
FILE MANAGEMENT PROCESS(READ,WRITE)

#include

<unistd.h>

#include

<sys/types.h>

#include <fcntl.h>

main()

int

fd1,fd2,n;

char *ch;

fd1=open("file1",

O_CREAT|O_RDWR,0666); if(fd1==-1)

printf("source filw cannot be

processed \n"); exit(0);

fd2=open("file2",O_CREAT|O_RDWR,0

666); if(fd2==-1)

printf("destination file cannot be

processed \n"); exit(0);

while(1)

n=read(fd1,ch

OS-CSL507 46
,1); if(n==0)

break;

write(fd2,ch,

1);

close(fd1

);

close(fd2

);

OUTPUT

vi file1

good

morning cc

filerw.c

./a.o

ut vi

file2

good morning

OS-CSL507 47
Program to Create Thread:

A thread, sometimes called light weight process (lwp), is a


basic unit of CPU utilization. It comprises a thread ID, a program counter, a
register set, and a stack.

Pthread:
The header file is used <pthread.h>. pthread refers to the POSIX
standard defining an APF for thread creation and synchronization. Pthread,
the thread extension of the POSIX standard, may be provide as either a user
or kernel-level library. This is a specification for thread behavior not an
implementation. OS designers may implement the specification in any way
they wish. Numerous system implement the pthread specification, including
solaris, Linux, Mac OS x, & Tru 64 UNIX. shareware implementations are
available in the public domain for the various windows OS as well.

Just as every process has a process ID, every thread has a thread
ID. Unlike the process ID, which is unique in the system, the thread ID has
significance only within the context of the process to which it belongs.

A thread ID is represented by the pthread_t data type


implementation are allowed to use a structure to represent the pthread_t data
type, so portable implementation can’t treat them as integer. Therefore, a
function must be used to compare two thread ID.

#include<pthread.h>
int pthread_equal(pthread_t tid1,pthread_t tid2)

OS-CSL507 48
Thread Creation:
Threads can be created by calling, the pthread_create function.

#include<pthread.h>
int pthread_create(pthread_t *restrict
tidp,const pthread_attr_t *restrict attr, void
*(*start_rtn)(void),void *restrict arg);

The memory location pointed to by tidp is set to the thread ID of the newly
created thread when pthread_create returns successfully. The attr argument is
used to customize various thread attributes we’ll set this to NULL to create a
thread with the default attributes

The newly created thread starts running at the address of the start_rtn
function. this function takes a single argument, arg, which is a type less pointer.
If you need to pass more than one argument to the start_rtn function, then you
need to store them in a structure and pass the address of the structure in arg.

Thread Terminal:-
If any thread within a process call exit, _Exit or _exit, then the entire
process terminates. Similarly, when the default action is to terminate the
process, a signal sent to a thread will terminate the entire process.

A signal thread can exit in three ways, thereby stopping its flow of control,
without terminating the entire process.

• The thread can simply return from the start routine the return
value is the thread’s exit code.
• The thread can be cancelled by another in the same process.
• The thread can call ptheread_exit.

OS-CSL507 49
#include<pthread.h>

void pthread_exit(void *rval_ptr);

The rval_ptr is a typeless pointer, similar to the signal argument passed to the
start routine. This pointer is available to other threads in the process by calling
the pthread_join function.

#include<pthread.h>

int pthread_join(pthread_t thread, void **rvl_ptr);

By calling pthread_join, we automatically place a thread in the detached state so


that its resources can be recovered. If the thread was already in the detached
state, calling pthread_join fails, returning EINVAL.

If we are not interested in a threads return value, e can set rval_ptr to NULL. In
this case, calling pthread_join allows us to wait for the specified thread, but does
not retrieve the thread’s termination status.

OS-CSL507 50
IMPLEMENTING A PROGRAM USING THREAD

#include<pthred.
h>
#include<stdio.h
>
#define NUM_THREADS 3
int
je,jo,evensum=0,sumn=0,oddsum=0,evenarr[50],od
darr[50];
void *Even(void *threadid)
{
int
i,n;
je=0;
n=(int)threadi
d;
for(i=1;i<=n;i+
+)
{
if(i%2==0
)
{
evenarr[je]=i;
evensum=evensu
m+i; je++;
}
}
}
void *Odd(void *threadid)
{
int
i,n;
jo=0;
n=(int)threadi
d;
for(i=0;i<=n;i+
+)
{
if(i%2!=0
)
{
oddarr[jo]=i;
oddsum=oddsu
m+i; jo++;
}
}
}
void *SumN(void *threadid)
{
OS-CSL507 51
int i,n;
n=(int)threadi
d;
for(i=1;i<=n;i+
+)
{
sumn=sumn+i;
}
}
int main()
{
pthread_t
threads[NUM_THREADS]; int
i,t;
printf("enter a
number\n");
scanf("%d",&t);
pthread_create(&threads[0],NULL,Even,(void
*)t);
pthread_create(&threads[1],NULL,Odd,(void*)
t);
pthread_create(&threads[2],NULL,SumN,(voi
d*)t); for(i=0;i<NUM_THREADS;i++)
{
pthread_join(threads[i],NULL);
}
printf("the sum of first N natural nos is
%d\n",sumn); printf("the sum of first N even
natural nos is %d\n",evensum); printf("the sum of
first N odd natural nos is %d\n",oddsum);
printf("the first N even natural nos is --\n");
for(i=0;i<je;i++)
printf("%d\n",evenar
r[i]); for(i=0;i<jo;i++);
printf("%d\n",oddarr
[i]);
pthread_exit(NULL);
}

OUTPUT:

For Compiling thread program we

have to type cc thread1.c –lpthread

For Running the program

./a.out

Enter a
number 12

OS-CSL507 52
The sum of first N natural nos
is 78 The sum of first N even
natural nos is The sum of first
N odd natural nos is The first
N even natural nos is
2
4
6
8
10
12
0

OS-CSL507 53
PRODUCER CONSUMER PROBLEM :
In computer science the producer consumer problem (also known as
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 store 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 its 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 remove an atom from the buffer, it wakeup the producer who
start 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 wakeup the sleeping consumer. The solution can be reached by means of IPC,
typically using semaphores.

Semaphores solve the problem of lost wakeup calls. In the solution below
we use two semaphores, fill count and empty count, to solve the problem. Fill
count is incremented and empty count is decremented when a new atom has
been put into the buffer. If the producer’s tries to decrement empty count while
its value is zero. The producer is put to sleep. The next time an item is consumed;
empty count is increment and the producer wake up. The consumer works
analogously.

SEMAPHORES :
They are synchronization primitive. They are not used for exchanging large
amount of data, but are intended to let multiple processes synchronize their
operation. A semaphore is an integer variable with two atomic operation wait and
signal.

Synopsis :
OS-CSL507 54
#include<sys/sem.h>

int semget (key_t, int nsems, int semflag)

The semget function returns the semaphores identifier associated with the
key parameter. The semget function create the identifier and its associated
semaphore set, if the key is IPC_PRIVATE or semflg and IPC_CREAT is nonzero
and no semaphore set or identifier is already associated with key.

Return value :
- If successful, semget returns a non negative integer corresponding to the
semaphore identifier.

- If unsuccessful, the semget functions returns -1 and set errno.

- IPC includes message queue, semaphore set and shared memory; provide
mechanism for sharing information among processes on the same system.
These three communication mechanisms have a similar structure.

Mechanism POSIX function Meaning


Message queue msgct Control
l Creat or acess
msgg Receive
et message Send
msgr message
cv
msgsnd
Semaphore semc Control
tl Creat or access
semg Execute operation
et (wait orpost)
semo
p

OS-CSL507 55
Shared memeory shmat Attach memory to
process Control
shmt Detached memory
l from process
shm Creat and
dt initialize or
access.
shmget

IPC_CREAT----- It ensures that if the semaphore set does not exist, semget
create it. The permission allow all user to access the semaphore set.

<sys/types.h> ----- This header file is used because


key_t data type is present in this file.

<sys/ipc.h> -- This header file IPC_CREAT, IPC_WAIT, IPC_EXCL


is present.

<sys/sem.h> - Creating semaphore

<sys/shm.h> - Creating shared memory

In producer consumer program—

Header file used :

Semid=semget ((key_t) 10, 1,IPC_CREAT|0666);

We are creating a semaphore using semget function with given parameters.

1) (key_t)10 ----- The name given to the semaphore and it will be stored in
hexadecimal.
2) 1 --------------- Number of bytes (size of semaphore)
3) IPC_CREAT|0666 -- Create mode permission.

OS-CSL507 56
Semaphore control : (semctl)
Each element of a semaphore set must be initialized with semctl before
it is used. This semctl function provides control operation in elements
semnum for the semaphore set semid.

SETVAL function:
It set the value of a specific semaphore element to arg valve.

- SETVAL is the value for cmd parameter rf semctl.

Semaphore set operation : (semop)

The semop function automatically performs a user defined


collection of semaphore operation on the semaphore set associated with
identifier semid.
- The sop parameter points to an array of element operations.
- If successful, semop returns 0. If unsuccessful, semop returns -1 and set
errno.
- The semop function performs all the operations specified in sop array
automatically on a single semaphore set.
- The struct sembuf structure,which specifies a semaphore element
operation, include the follwoing members.

short sem_nu ------- number of semaphore elements


short sem_op ------- particular element operation to be performed
shor sem_flg---------flags to specify the option for the operation

OS-CSL507 57
- The sem_op element operation are values specifiying te amount by which
the semaphore alue is to be changed:
1. If sem_op is an integer greater than zero, semop adds the value to the
corresponding semaphore element value and awakens all process that is
waiting for the element to increase.
2. If sem_op and the semaphore element value is not 0, semop blocks the
calling process (waiting for 0) and increment the count of processes waiting
for zero value of that element.
3. If sem_op is a negative number, semop adds the sem_op value to the
corresponding semaphore element value provided that the result would
not be negative. If the operation would make the semaphore element value
increases. If the resulting value is zero, semop wales the processes waiting
for 0.

Shared memory :
Shared memory allows process to read and write from the same memory
segment. The <sys/shm.h> header file defines the data structure for shared
memory.

Synopsis:

#include<sys/shm.h>
int shmget (key_t key, size_t size, int shmflg)

The shmget function returns an identifier for the shared memory segment
associated with key parameter. It creates the segment if either the key is
IPC_PRIVATE or shmflg or IPC_CREAT is nonzero and no shared memory
segment or identifier is already associated with the key.

- If successful, shmget returns a non negative integer corresponding to the


shared memory segment identifier.
- If unsuccessful, shmget returns -1 and set errno.

OS-CSL507 58
Attaching and detaching a shared memory segment :
The shmat function attaches the shared memory segment specified by
shmid to the address space of the calling process and increments the value
of shm_nattch for shmid. The shmat function returns a void *pointer, so a
program can use the return value like an ordinary pointer obtained from
malloc.

- If successful, shmat returns the starting address of the segment.


- If unsuccessful, shmat returns -1 and set errno.

Here, in producer consumer program—

shmid = shmget ((key_t)11,100,IPC_CREAT|0666);

The shmget () is passed with three parameters.

1) (key_t) 11 name given to the segment with decimal value.


2) 100 ----------- signifying the number of bytes, we want to resolve for the block.
3) IPC_CREAT ----- create with read-write, read-write, read-write permission.

Message queues :
The message queue is a POSIX: XSI IPC mechanism that allows a
process to send and receive messages from other processes. The data
structures for message queue are defined in
<sys/msg.h>. The major data structure for message is msqid_ds.

Synopsis :

#include<sys/msg.h>
int msgget (key_t key, int msgflg);

The msgget function returns the message queue identifier associated with
the key parameter. It creates the identifier if either the key is IPC_PRIVATE or
msgfig and IPC_CREAT is non zero and no message queue or identifier is already
associated with key.

If successful, msgget returns a non –ve integer corresponding to the message

OS-CSL507 59
queue identifier. If unsuccessfull, msgget returns -1 and set errno.

MESSAGE SEND() :-
After obtaining access to an mssage queue with msgget, a program inserts
messages into the queue with msgsnd. The msqid parameter identifies the
message queue, and the msgp parameter points to a user-defined buffer that
contains the message to be sent, the msgsz parameter specifies the actual size of
the message text, and the msgfig parameter specifies actions to be taken under

#include<sus/msg.h>
int msgsnd(int msqid,const void *msgp,size_t msgsz,int msgflag);
various conditions.

If successful, msgsnd returns 0

If unsuccessful, msgsnd returns -1 and sets errno.

MESSAGES RECEIVE() :-
A program can remove a message from a message queue with msgrcu. The
msqid parameter identifies the message queue, and the msgp parameter points
to a user-defined buffer for holding the message to be retrieved. The format of
msgp is as described above for msgsnd. The

Msgsz parameter specifies the actual size of the message text. The msgtyp
parameter can be used by the received for message selection. The msgflg specifies
actions to be taken under various conditions.

#include<sys/msg.h>
Size_t msgrcv(int msqid,void *msgp,size_t msgsz,long msgtyp,int msgflg);

If successful, msgrcv returns the no. Of bytes int the text of

the message. If unsuccessful, msgrcv returns (size_t) -1 and

sets errno.

OS-CSL507 60
In producer-consumer program

Msgqidmsgget(key,IPC_CREAT|0666);

Message queues are created using the msgget () Function. It takes two
parameters the name of the message queue also knows as key and flg which can
be one or both of the following.

The msgp parameter points to a user-defined buffer whose first member must be
specifying the type of message, followed by space for the text of the message. The
structure might be defined as follows.

Struct databuf
{
Int mtpe; //message type
Char arr; //message text
}send,recv;
The message type must be greater than 0. The user can assign message type
in any way
appropriate to the application.

OS-CSL507 61
IMPLEMENTATION OF PRODUCER AND CONSUMER
PROBLEM USING SEMAPHORES

#include<stdio.
h>
#include<stdlib
.h>

int

mutex=1,full=0,empty=3,x=

0; int main()
{
int n;
void
producer();
void
consumer();
int wait(int);
int signal(int);
printf("\n1.producer\n2.consumer
\n3.exit"); while(1)
{
printf("\nenter your
choice:");
scanf("%d",&n);
switch(n)
{
case 1 : if((mutex==1) &&
(empty!=0)) producer();
else
printf("buffer is
full!"); break;
case 2 : if((mutex==1) &&
(full!=0)) consumer();
else
printf("buffer is
empty!!"); break;
case 3 :
exit(0);
break;
}
}
return 0;
}

int wait(int s)
{
return(--s);

OS-CSL507 62
}

int signal(int s)
{
return(++s);
}
void producer()
{
mutex=wait(mut
ex);
full=signal(full);
empty=wait(emp
ty); x++;
printf("\nProducer produces the
item %d",x); mutex=signal(mutex);
}
void consumer()
{
mutex=wait(mute
x); full=wait(full);
empty=signal(emp
ty);
printf("\nconsumer consumes item
%d",x); x--;
mutex=signal(mutex);
}

OS-CSL507 63
DINNING – PHILOSPHERS PROBLEM :-
Consider five PHILOSPHERS who spend their lives thinking and eating.
The PHILOSPHERS share a circular table surrounded by five chairs, each
belonging to one PHILOSPHER. In the center of the table is a bowl of rice, and
the table is laid with five single chopsticks as shown in figure mentioned below:

Rice

Fig: Structure of the dinning philosophers.

When a philosopher thinks, she does not interact with her colleagues; a
philosopher gets hungry and tries to pick up the two chopsticks that are closest
to her. A philosopher may pick up only one chopstick at a time. She cannot pick
up a chopstick that is already in the hand of a neighbor. When a hungry
philosopher has both her chopsticks at the same time, she eats releasing her
chopsticks. When she is finished eating, she puts down both of her chopsticks
and start thinking again.

OS-CSL507 64
The dinning-philosophers problem is consider a classic synchronization
problem because it is an example of a large class of concurrency-control
problem.

One simple solution is to represent each chopstick with a semaphore. A


philosopher tries to grab a chopstick by executing a wait ()

Operation on that semaphore, she release her chopstick by executing


the signal () operation on the appropriate semaphore. Thus, the shared data

Semaphore chopstick[5];
are:

Where all the elements of the chopstick are initialized to 1. The structure of
philosopher I is shown in figure mention below:

do{
Wait(chopsticki]);
Wait(chopstick(i+1)%5);
……..
//eat
……..
Signal(chopstick[i]);
Signal(chopstick[i+1]%5);
……….
//think
……….
}while(TRUE);
Fig: Structure of Philosopher i.

Although this solution guarantees that no two neighbors are eating


simultaneously, it nevertheless must be rejected because it could create a
deadlock. Suppose that all five philosophers become hungry simultaneously and
each grabs her left chopstick. All the elements of the chopstick will now be equal
to 0. When each philosopher tries to grab her right chopstick she will be delayed
forever.

OS-CSL507 65
IMPLEMENTATION OF DINING PHILOSOPHER USING SEMAPHORE
#include<stdio.h>

#include<stdlib.h>

#include<pthread.h

>

#include<semaphor

e.h>

#include<unistd.h>

sem_t room;

sem_t chopstick[5];

void *

philosopher(void *);

void eat(int);

int main()

int i,a[5];

pthread_t

tid[5];

sem_init(&room,0,4);

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

sem_init(&chopstick[i],0

,1);

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

a[i]=i;

OS-CSL507 66
pthread_create(&tid[i],NULL,philosopher,(void*) &a[i]);

}
for(i=0;i<5;i++)

pthread_join(tid[i],NULL)

void * philosopher(void * num)

int phil=*(int*)num;

sem_wait(&room);

printf("\nPhilosopher %d has entered

room",phil); sem_wait(&chopstick[phil]);

sem_wait(&chopstick[(phil+1)%5]);

eat(phil

);

sleep(2)

printf("\nphilosopher %d has finished eating",phil);

sem_post(&chopstick[(phil+1)%5

]); sem_post(&chopstick[phil]);

sem_post(&room);

void eat(int phil)

OS-CSL507 67
{

printf("\nphilosopher %d is eating",phil);

OS-CSL507 68
6. WRITE A PROGRAM TO IMPLEMENT PROCESSOR
SCHEDULING ALGORITHMS
A) FCFS B) SJF

First Come First Serve (FCFS) is an operating system scheduling algorithm


that automatically executes queued requests and processes in order of their
arrival. It is the easiest and simplest CPU scheduling algorithm. In this type of
algorithm, processes which requests the CPU first get the CPU allocation first.
This is managed with a FIFO queue. The full form of FCFS is First Come First
Serve.

As the process enters the ready queue, its PCB (Process Control Block) is
linked with the tail of the queue and, when the CPU becomes free, it should be
assigned to the process at the beginning of the queue.

OS-CSL507 69
FCFS PROCESSOR SCHEDULING PROGRAM

#include<stdio

.h> Int main()

int n,bt[20],wt[20],tat[20],avwt=0,avtat=0,i,j;

printf("Enter total number of

processes(maximum 20):"); scanf(“%d”,&n);

printf("nEnter Process Burst

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

Printf(“p[%d]:”,i+1);

Scanf(“%d”,&bt[i]);

wt[0]=

0;

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

wt[i]=0;

for(j=0;j<i;j+

+)

wt[i]+=bt[j];

printf("nProcessttBurst TimetWaiting

TimetTurnaround Time"); for(i=0;i<n;i++)

tat[i]=bt[i]+wt[

i]; avwt+=wt[i];

OS-CSL507 70
avtat+=tat[i];

printf("nP[%d]tt%dtt%dtt%d",i+1,bt[i],wt[i],tat[i]);

avwt/

=i;

avtat/

=i;

printf("nnAverage Waiting

Time:%d",avwt); printf("nAverage

Turnaround Time:%d",avtat);

OUTPUT:

SJF PROCESS SCHEDULING ALGORITHM


OS-CSL507 71
• Shortest Job first has the advantage of having a minimum average
waiting time among all scheduling algorithms.
• It is a Greedy Algorithm.
• It may cause starvation if shorter processes keep coming. This problem
can be solved using the concept of ageing.
• It is practically infeasible as Operating System may not know burst
time and therefore may not sort them. While it is not possible to predict
execution time, several methods can be used to estimate the execution
time for a job, such as a weighted average of previous execution times.
SJF can be used in specialized environments where accurate estimates of
running time are available.
Algorithm:

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

2. Then select that process which has minimum arrival time and minimum
Burst time.

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

OS-CSL507 72
• SJF PROCESSOR SCHEDULING PROGRAM

#include<stdi

o.h> int

main()

int

bt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,t

emp; float avg_wt,avg_tat;

printf("Enter number of process:");

scanf("%d",&n);

printf("\nEnter Burst

Time:\n");

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

printf("p%d:",i+1);

scanf("%d",&b

t[i]); p[i]=i+1;

//sorting of burst

times

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

pos=i;

for(j=i+1;j<n;

j++)

OS-CSL507 73
if(bt[j]<bt[p

os]) pos=j;

temp=bt[i];

bt[i]=bt[pos];

bt[pos]=te

mp;

temp=p[i];

p[i]=p[pos];

p[pos]=tem

p;

wt[0]=

0;

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

wt[i]=0;

for(j=0;j<i;j

++)

wt[i]+=bt

[j];

total+=wt[i

];

avg_wt=(float)total/

n; total=0;

OS-CSL507 74
printf("\nProcess\t Burst Time \tWaiting

Time\tTurnaround Time"); for(i=0;i<n;i++)

tat[i]=bt[i]+w

t[i];

total+=tat[i];

printf("\np%d\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);

}
avg_tat=(float)total/n;

printf("\n\nAverage Waiting

Time=%f",avg_wt); printf("\nAverage

Turnaround Time=%f\n",avg_tat);}

OUTPUT

OS-CSL507 75
BANKERS ALGORITHM FOR DEAD LOCK AVOIDANCE

The banker’s algorithm is a resource allocation and deadlock avoidance


algorithm that tests for safety by simulating the allocation for
predetermined maximum possible amounts of all resources, then makes
an “s-state” check to test for possible activities, before deciding whether
allocation should be allowed to continue.
Why Banker’s algorithm is named so?
Banker’s algorithm is named so because it is used in banking system to
check whether loan can be sanctioned to a person or not. Suppose there
are n number of account holders in a bank and the total sum of their
money is S. If a person applies for a loan then the bank first subtracts
the loan amount from the total money that bank has and if the
remaining amount is greater than S then only the loan is sanctioned. It
is done because if all the account holders comes to withdraw their money
then the bank can easily do it.
In other words, the bank would never allocate its money in such a way
that it can no longer satisfy the needs of all its customers. The bank
would try to be in safe state always.

Following Data structures are used to implement the Banker’s Algorithm:


Let ‘n’ be the number of processes in the system and ‘m’ be the
number of resources types.
Example:
Considering a system with five processes P0 through P4 and three
resources of type A, B, C. Resource type A has 10 instances, B has 5
instances and type C has 7 instances. Suppose at time t0 following
snapshot of the system has been taken:

Question1. What will be the content of the Need matrix?

OS-CSL507 76
Need [i, j] = Max [i, j] – Allocation

[i, j] So, the content of Need

Matrix is:

Question2. Is the system in a safe state? If Yes, then what is the safe
sequence?
Applying the Safety algorithm on the given system,

OS-CSL507 77
7. WRITE A PROGRAM TO SIMULATE BANKERS ALGORITHM FOR DEAD
LOCK AVOIDANCE
#include<stdio
.h> int main()
{
int n,m,i,j,k;

n=5;//number of
processes
m=3;//number of
resources
int alloc[5][3]= { {0,1,0},{2,0,0},{3,0,2},{2,1,1},{0,0,2}};//allocation matrix
int max[5][3]= { {7,5,3},{3,2,2},{9,0,2},{2,2,2},{4,3,3}};//max matrix
int avail[3]= {3,3,2};//available resources

int
f[n],ans[n],ind=0;
for(k=0;k<n;k++)
{
f[k]=0
;
}
int
need[n][m];
for(i=0;i<n;i+
+)
{
for(j=0;j<m;j++)
need[i][j]= max[i][j]-alloc[i][j];
}

OS-CSL507 78
int y=0;
for(k=0;k<5;k+
+){
for(i=0;i<n;i++){
if(f[i]==0){
int flag=0;
for(j=0;j<m;j+
+)
{
if(need[i][j]>avail[j])
{ flag=1;
break;
}
}
if(flag==0){
ans[ind++]=i;
for(y=0;y<m;y++)
avail[y]+=alloc[i][j];
f[i]=1;
}
}
}
}
printf("following is the safe
sequence\n"); for(i=0;i<n-1;i++)
printf("P%d->",ans[i]);
printf("P%d",ans[n-1]);
return(0);

OUTPUT
Following is the SAFE Sequence
P1 -> P3 -> P4 -> P0 -> P2

OS-CSL507 79
8. WRITE A PROGRAM TO IMPLEMENT PAGE REPLACEMENT ALGORITHMS:
A) FIFO b) LRU
First In First Out (FIFO) –
This is the simplest page replacement algorithm. In this algorithm, the
operating system keeps track of all pages in the memory in a queue, the oldest
page is in the front of the queue. When a page needs to be replaced page in the
front of the queue is selected for removal.
Example-1Consider page reference string 1, 3, 0, 3, 5, 6 with 3 page
frames.Find number of page faults.

Algorithm for FIFO Page


Replacement

• Step 1. Start to traverse the pages.


• Step 2. If the memory holds fewer pages, then the capacity else goes to step 5.
• Step 3. Push pages in the queue one at a time until the queue
reaches its maximum capacity or all page requests are fulfilled.
• Step 4. If the current page is present in the memory, do nothing.
• Step 5. Else, pop the topmost page from the queue as it was inserted first.
• Step 6. Replace the topmost page with the current page from the string.
• Step 7. Increment the page faults.
• Step 8. Stop

OS-CSL507 80
Initially all slots are empty, so when 1, 3, 0 came they are allocated to the
empty slots —> 3 Page Faults.
when 3 comes, it is already in memory so —> 0 Page Faults.
Then 5 comes, it is not available in memory so it replaces the oldest page slot
i.e 1. —>1 Page Fault.

6 comes, it is also not available in memory so it replaces the oldest page slot
i.e 3 —>1 Page Fault.
Finally when 3 come it is not avilable so it replaces 0 1 page fault

OS-CSL507 81
FIFO PAGE REPLACEMEMT ALGORITHM PROGRAM
#include<stdio.
h>
#include<stdlib
.h> struct
fnode
{
int pno;
}frames[5];
int ref_str[]={3,4,5,6,3,4,7,3,4,5,6,7,2,4,6};
int
pfct=0,i,n,pno,p,flag=
0; int len=15;
int page_found(int pno)
{
for(i=0;i<n;i++)
if(frames[i].pno==pno)
return i;
return 0;
}
main()
{
printf("\nenter no of
frames:"); scanf("%d",&n);
printf("len:%d",le
n);
for(i=0;i<n;i++)
frames[i].pno=-
1;

OS-CSL507 82
printf("\n page no page frames
page_fault pfct"); printf("\n \n");
for(p=0;p<len;p++)
{
pno=ref_str[
p]; flag=0;
if(page_found(pno)==0)
{
frames[pfct%n].pno=
pno; pfct++;
flag=1;
}
printf("\n%fd\t",pno);
for(i=0;i<n;i++)
printf("%d",frames[i]);
if(flag==1)
printf("\t
yes"); else
printf("\t no");
printf("\t%d",pfct);
}
printf("\n ");
printf("\n total no of page fault :
%d",pfct);
}
Least Recently Used –
In this algorithm page will be replaced which is least recently used.
Example-3Consider the page reference string 7, 0, 1, 2, 0, 3, 0, 4, 2, 3,
0, 3, 2 with 4 page frames.Find number of page faults.

OS-CSL507 83
Initially all slots are empty, so when 7 0 1 2 are allocated to the empty
slots —> 4 Page faults
0 is already their so —> 0 Page fault.
when 3 came it will take the place of 7 because it is least recently used —>1
Page fault
0 is already in memory so —> 0
Page fault. 4 will takes place of 1 —

> 1 Page Fault


Now for the further page reference string —> 0 Page fault because they
are already available in the memory.

OS-CSL507 84
LRU PAGE REPLACEMEMT ALGORITHM PROGRAM
#include<stdio
.h> struct
frame
{
int pno;

int counter;
}frames[5];
int ref_str[]={12,15,12,18,6,8,11,12,19,12,6,8,12,15,19,8}
int
np=15,n,i,j,currtim
e; int
page_found(int
pno)
{
int i;
for(i=0;i<n;i+
+)
if(frames[i].pno==pno)
return i;
return -1;
}
int get_lru()
{
int min=0;
for(i=0;i<n;i+
+)
if(frames[i].counter<frames[min].count
er) min=i;
return min;

OS-CSL507 85
}
int main()
{
int i,j,pno,p,page_fault=0,flag;
printf(“\nenter how many
frames :”); scanf(“%d”,&n);
for(i=0;i<n;i++)
{
frames[i].pno=-1;
frames[i].counter
=-1;
}
printf(“\n page no \t frames \t
page fault”); printf(“\n “);
currtime=1;
for(p=0;p<np;p
++)
{
flag=0;
pno=ref_str[p];
j=page_found(p
no); if(j==-1)
{
page_fault++;
j=get_lru();
frames[j].pno=p
no; flag=1;
}

OS-CSL507 86
frames[j].counter=currtime;
currtime++;
printf(“\n%5d\t”,p
no); for(i=0;i<n;i++)
printf(“%2d:%2d”,frames[i].pno,frames[i].cou
nter); if(flag==1)
printf(“\t
yes); else
printf((“\t no”);
}
printf(“\n “);
printf(“\n no of page fault :
%d”,page_fault

OS-CSL507 87
9. WRITE A PROGRAM TO IMPLEMENT DISK SCHEDULING ALGORITHMS.
A) FCFS B) SCAN
FCFS DISK SCHEDULING ALGORITHM
Given an array of disk track numbers and initial head position, our task is
to find the total number of seek operations done to access all the requested
tracks if First Come First Serve (FCFS) disk scheduling algorithm is
used.
First Come First Serve (FCFS)
FCFS is the simplest disk scheduling algorithm. As the name suggests,
this algorithm entertains requests in the order they arrive in the disk
queue. The algorithm looks very fair and there is no starvation (all
requests are serviced sequentially) but generally, it does not provide the
fastest service.
Algorithm:
1. Let Request array represents an array storing indexes of tracks that
have been requested in ascending order of their time of arrival. ‘head’ is the
position of disk head.

2. Let us one by one take the tracks in default order and calculate the
absolute distance of the track from the head.
3. Increment the total seek count with this distance.
4. Currently serviced track position now becomes the new head position.
5. Go to step 2 until all tracks in request array have not been serviced.
Example:
Input:

Request sequence = {176, 79, 34, 60, 92, 11, 41, 114}Initial head
position = 50

Output:
Total number of seek operations = 510
Seek Sequence is
176
79
34
60
92
11
41
114

OS-CSL507 88
The following chart shows the sequence in which requested tracks are
serviced using FCFS.

Therefore, the total seek count is calculated as:

= (176-50)+(176-79)+(79-34)+(60-34)+(92-60)+(92-11)+(41-11)+(114-41)
= 510

OS-CSL507 89
PROGRAM FOR FCFS DISK SCHEDULING ALGORITHM

#include<stdio.h>
int main()
{
int
queue[20],n,head,i,j,k,seek=0,max,
diff; float avg;
printf("Enter the max range of
disk\n"); scanf("%d",&max);
printf("Enter the size of queue
request\n"); scanf("%d",&n);
printf("Enter the queue of disk positions to
be read\n"); for(i=1;i<=n;i++)
scanf("%d",&queue[i]);
printf("Enter the initial head
position\n"); scanf("%d",&head);
queue[0]=head;
for(j=0;j<=n-
1;j++)
{
diff=abs(queue[j+1]-queue[j]);
seek+=diff;
printf("Disk head moves from %d to %d with seek
%d\n",queue[j],queue[j+1],diff);
}
printf("Total seek time is
%d\n",seek); avg=seek/(float)n;
printf("Average seek time is
%f\n",avg); return 0;
}

OS-CSL507 90
SCAN DISK SCHEDULING ALGORITHM

Given an array of disk track numbers and initial head position, our task
is to find the total number of seek operations done to access all the
requested tracks if SCAN disk scheduling algorithm is used.

SCAN (Elevator) algorithm


In SCAN disk scheduling algorithm, head starts from one end of the disk
and moves towards the other end, servicing requests in between one by
one and reach the other end. Then the direction of the head is reversed
and the process continues as head continuously scan back and forth to
access the disk. So, this algorithm works as an elevator and hence
also known as the elevator algorithm. As a result, the requests at the
midrange are serviced more and those arriving behind the disk arm will
have to wait.
Advantages of SCAN (Elevator) algorithm
1. This algorithm is simple and easy to understand.
2. SCAN algorithm have no starvation.
3. This algorithm is better than FCFS Scheduling algorithm .
Disadvantages of SCAN (Elevator) algorithm
1. More complex algorithm to implement.
2. This algorithm is not fair because it cause long waiting time for the
cylinders just visited by the head.
3. It causes the head to move till the end of the disk in this way the requests
arriving ahead of the arm position would get immediate service but some
other requests that arrive behind the arm position will have to wait for the
request to complete.

ALGORITHM

1. Let Request array represents an array storing indexes of tracks that


have been requested in ascending order of their time of arrival. ‘head’ is the
position of disk head.
2. Let direction represents whether the head is moving towards left or right.
3. In the direction in which head is moving service all tracks one by one.
4. Calculate the absolute distance of the track from the head.
5. Increment the total seek count with this distance.
6. Currently serviced track position now becomes the new head position.
7. Go to step 3 until we reach at one of the ends of the disk.
8. If we reach at the end of the disk reverse the direction and go to step 2
until all tracks in request array have not been serviced.

OS-CSL507 91
Example:
Input:
Request sequence = {176, 79, 34, 60, 92, 11, 41, 114}Initial head
position = 50
Direction = left (We are moving from right to left)

Output:
Total number of seek operations = 226
Seek Sequence is
41
34
11
0
60
79
92
114
176

The following chart shows the sequence in which requested tracks are
serviced using SCAN.

Therefore, the total seek count is calculated as:


= (50-41)+(41-34)+(34-11)
+(11-0)+(60-0)+(79-60)
+(92-79)+(114-92)+(176-114)
= 226

OS-CSL507 92
PROGRAM FOR SCAN DISK SCHEDULING ALGORITHM

#include<conio.h>
#include<stdio.h>
int main()
{
int i,j,sum=0,n;
int d[20];
int disk; //loc of head
int temp,max;
int dloc; //loc of disk in array
clrscr();
printf("enter number of location\t");
scanf("%d",&n);
printf("enter position of head\t");
scanf("%d",&disk);
printf("enter elements of disk queue\n");
for(i=0;i<n;i++)
scanf("%d",&d[i]);
}
d[n]=dis
k;
n=n+1;
for(i=0;i<n;i++) // sorting disk locations
{
for(j=i;j<n;j++)
{
if(d[i]>d[j])
{
temp=d[i
];
d[i]=d[j];
d[j]=tem
p;
}
}
}
max=d[n];

OS-CSL507 93
for(i=0;i<n;i++) // to find loc of disc in array
{
if(disk==d[i]) { dloc=i; break; }
}
for(i=dloc;i>=0;i--)
{
printf("%d -->",d[i]);
}
printf("0 -->");
for(i=dloc+1;i<n;i+
+)
{
printf("%d-->",d[i]);
}
sum=disk+max;
printf("\nmovement of total cylinders
%d",sum); getch();
return 0;
}
Output:
Enter no of location
8 Enter position of
head 53
Enter elements of disk
queue 98
183
37
122
14
124
65
67
53->37->14->0->65->67->98->122->124->183->
Movement of total cylinders 236.

OS-CSL507 94
OS-CSL507 95

You might also like