Updated OS Lab11
Updated OS Lab11
V SEMESTER
Batch: 2019-2023
Prepared by
_______________ _________________
Faculty Signature Head of Department
OS-CSL507 1
Vision:
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
OS-CSL507 2
8. Apply ethical principles and commit to professional ethics and responsibilities towards
working environment
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:
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.
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).
1 2 3 n
OPERATING SYSTEM
COMPUTER
HARDWARE
OS-CSL507 7
PROCESS :-
PROGRAM :-
It is an executable file.
It is usually created by link editor and recites on disk files.
SYSTEM CALL :-
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.
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.
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:
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.
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:
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.
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.
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.
ROOT
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
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.
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.
Example:
3. Remove :-
OS-CSL507 15
Syntax:
rm [Option] SourceFileName
rm [Option] Source1 Source2
4. Mkdir:-
Syntax :
mkdir DirectoryName
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
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:
6. Rmdir :-
OS-CSL507 17
Syntax:
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
$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
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.
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 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.
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.
Compilation command :
cc Filename.c
Where,
cc is the c-compiler.
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.
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:
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.
Execv(path, args)
Execvp(file, args)
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).
➢ Execue () :
OS-CSL507 28
• It executes a process in an environment which it assigns.
#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.
* barrier
* lock/semaphore
* non-blocking synchronization
<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:
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
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
OS-CSL507 39
Message Queues
Shared Memory
OS-CSL507 40
Semaphore
Semaphore Definition:-
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);
OUTPUT
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);
OUTPUT
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)
fd2=open("file2",O_CREAT|O_RDWR,0
666); if(fd2==-1)
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:
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.
#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>
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>
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:
./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>
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.
- 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.
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.
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.
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.
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.
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.
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.
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);
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
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.
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.
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)
int phil=*(int*)num;
sem_wait(&room);
room",phil); sem_wait(&chopstick[phil]);
sem_wait(&chopstick[(phil+1)%5]);
eat(phil
);
sleep(2)
sem_post(&chopstick[(phil+1)%5
]); sem_post(&chopstick[phil]);
sem_post(&room);
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
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
int n,bt[20],wt[20],tat[20],avwt=0,avtat=0,i,j;
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
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:
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
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
tat[i]=bt[i]+w
t[i];
total+=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
OS-CSL507 76
Need [i, j] = Max [i, j] – Allocation
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.
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 —
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.
= (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.
ALGORITHM
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.
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