Record6 10
Record6 10
INTRODUCTION
Inter-Process Communication (IPC) is a set of techniques for the exchange of data among two or
more 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, synchroniation, shared
memory, and remote proced!re ca""s (PC). !he method of IPC used may vary based on the bandwidth
and "atency of communication between the threads, and the type of data being communicated. IPC may a"so
be referred to as inter-thread communication and inter-application communication.IPC, on pair with the
address space concept, is the foundation for address space.
PARENT C#I$D PROCESS
IPC dea"s main"y with the techniques and mechanisms that faci"itate communication between
processes. #et us start from something primitive. $e %now that some medium or other is required for
communication between different processes. &imi"ar"y, when it comes to computer programs, we need some
mechanism or medium for communication. Primari"y, processes can use the avai"ab"e memory to
communicate with each other. 'ut then, the memory is comp"ete"y managed by the operating system. (
process wi"" be a""otted some part of the avai"ab"e memory for execution. !hen each process wi"" have its
own unique user space. In no way wi"" the memory a""otted for one process over"ap with the memory
a""otted for another process.
!he operating system)s %erne", which has access to a"" the memory avai"ab"e, wi"" act as the
communication channe". !here are different IPC mechanisms which come into use based on the different
requirements.
%asic IPC
!he IPC mechanisms can be c"assified into the fo""owing categories as given be"ow*
pipes
fifos
shared memory
mapped memory
message queues
soc%ets
&' PIPES
Pipes were evo"ved in the most primitive forms of the +nix operating system. !hey provide unidirectiona"
f"ow of communication between processes within the same system. In other words, they are ha"f-dup"ex,
that is, data f"ows in on"y one direction. ( pipe is created by invo%ing the pipe system ca"", which creates a
pair of fi"e descriptors. !hese descriptors point to a pipe inode and the fi"e descriptors are returned through
the fledes argument. In the fi"e descriptor pair, fledes[0] is used for reading whereas fledes[1] is used
for writing.
(hat is a pipe)
Conceptua""y a pipe can be thought of much "i%e a hose-pipe, in that it is a conduit where we pour data in at
one end and it f"ows out at the other. ( pipe "oo%s a "ot "i%e a fi"e in that it is treated as a sequentia" data
stream. +n"i%e a fi"e, a pipe has two ends, so when we create a pipe we get two end points bac% in return.
$e can write to one end point and read from the other. ("so un"i%e a fi"e, there is no physica" storage of data
when we c"ose a pipe, anything that was written in one end but not read out from the other end wi"" be "ost.
$e can i""ustrate the use of pipes as conduits between processes in the fo""owing diagram*
,ere we see two processes which I-ve ca""ed Parent and Chi"d, for reasons that wi"" become apparent
short"y. !he Parent can write to Pipe A. and read from Pipe B. !he Child can read from Pipe A and write
to Pipe B.
.ote that each pipe can be used to send a request or return data depending upon which process is initiating
the transaction' !his gives us an interesting cha""enge in naming the pipes which we-"" discuss a "itt"e "ater.
!he common #inux she""s a"" a""ow redirection. /or examp"e
* "s + pr + "pr
pipes the output from the "s command "isting the directory-s fi"es into the standard input of the pr
command which paginates them. /ina""y the standard output from the pr command is piped into the standard
input of the "pr command which prints the resu"ts on the defau"t printer. Pipes then are unidirectiona" byte
streams which connect the standard output from one process into the standard input of another process.
.either process is aware of this redirection and behaves 0ust as it wou"d norma""y. It is the she"" which sets
up these temporary pipes between the processes.
In #inux, a pipe is imp"emented using two fle data structures which both point at the same
temporary 1/& inode which itse"f points at a physica" page within memory. each fle data structure contains
pointers to different fi"e operation routine vectors2 one for writing to the pipe, the other for reading from the
pipe.
!his hides the under"ying differences from the generic system ca""s which read and write to ordinary
fi"es. (s the writing process writes to the pipe, bytes are copied into the shared data page and when the
reading process reads from the pipe, bytes are copied from the shared data page. #inux must synchroni3e
access to the pipe. It must ma%e sure that the reader and the writer of the pipe are in step and to do this it
uses "oc%s, wait queues and signa"s.
IMP$EMENTATION
!he first thing to do is see how we use pipes to send and receive data. $e create a pipe using the
os.pipe() function which returns two ,i"e descriptors, one for each end of the pipe. $e can then use the
os.read/write functions to send data a"ong the pipe. *
import os
#et us exp"ain a scenario where we can use the pipe system ca""* consider a %eyboard-reader
program which simp"y exits after any a"pha-numeric character is pressed on the %eyboard. $e wi"" create
two processes2 one of them wi"" read characters from the %eyboard, and the other wi"" continuous"y chec%
for a"pha-numeric characters.
4ne ma0or feature of pipe is that the data f"owing through the communication medium is transient,
that is, data once read from the read descriptor cannot be read again. ("so, if we write data continuous"y into
the write descriptor, then we wi"" be ab"e to read the data on"y in the order in which the data was written.
&o, what happens when the pipe system ca"" is invo%ed5 ( good "oo% at the manua" entry for pipe
suggests that it creates a pair of fi"e descriptors. !his suggests that the %erne" imp"ements pipe within the
fi"e system. ,owever, pipe does not actua""y exist as such - so when the ca"" is made, the %erne" a""ocates
free inodes and creates a pair of fi"e descriptors as we"" as the corresponding entries in the fi"e tab"e which
the %erne" uses. ,ence, the %erne" enab"es the user to use the norma" fi"e operations "i%e read, write, etc.,
which the user does through the fi"e descriptors. !he %erne" ma%es sure that one of the descriptors is for
reading and another one it for writing.
Spawning processes
!he mechanism used for spawning a chi"d process is to use the os.fork() system ca"". !his returns
different va"ues depending on whether you are in the origina", parent process or in the new chi"d process. In
the origina" process the returned va"ue is the process I6 or pid of the chi"d process. If you are in the chi"d
process then the return va"ue from fork is 3ero. !his means that in the code we wi"" have an if statement that
tests the fork() return va"ue and if it is 3ero performs the chi"d functions and if non 3ero does the parent
function. !o %eep things manageab"e it is usua""y best to put those functions into separate modu"es and ca""
the functions as required.
ANA$O-.
Processes can communicate via pipes
Parents can spawn a c"one of themse"ves using os.fork
Chi"d processes need to be terminated or they wi"" run forever consuming va"uab"e computer
resources. $e can terminate a chi"d process using the os.kill function.
Reading /rom and (riting to a Named Pipe
eading from and writing to a named pipe are very simi"ar to reading and writing from or to a norma"
fi"e. !he standard C "ibrary function ca""s read( ) and write( ) can be used for reading from and writing to
a named pipe. !hese operations are b"oc%ing, by defau"t.
!he fo""owing points need to be %ept in mind whi"e doing read7writes to a named pipe*
( named pipe cannot be opened for both reading and writing.
!he process opening it must choose either read mode or write mode.
!he pipe opened in one mode wi"" remain in that mode unti" it is c"osed.
ead and write operations to a named pipe are b"oc%ing, by defau"t.
!herefore if a process reads from a named pipe and if the pipe does not have data in it, the reading
process wi"" be b"oc%ed. &imi"ar"y if a process tries to write to a named pipe that has no reader, the writing
process gets b"oc%ed, unti" another process opens the named pipe for reading. !his, of course, can be
overridden by specifying the 48.4.'#4C9 f"ag whi"e opening the named pipe. &ee% operations (via the
&tandard C "ibrary function "see%) cannot be performed on named pipes.
%ene,its o, Named Pipes
.amed pipes are very simp"e to use.
mkffo is a thread-safe function.
.o synchroni3ation mechanism is needed when using named pipes.
$rite (using write function ca"") to a named pipe is guaranteed to be atomic. It is atomic even if the
named pipe is opened in non-b"oc%ing mode.
.amed pipes have permissions (read and write) associated with them, un"i%e anonymous pipes.
!hese permissions can be used to enforce secure communication.
$imitations o, Named Pipes
.amed pipes can on"y be used for communication among processes on the same host machine.
.amed pipes can be created on"y in the "oca" fi"e system of the host, that is, you cannot create a
named pipe on the ./& fi"e system.
6ue to their basic b"oc%ing nature of pipes, carefu" programming is required for the c"ient and server,
in order to avoid dead"oc%s.
.amed pipe data is a byte stream, and no record identification exists.
0' MESSA-E 1UEUE
DE/INITION
In programming, message queueing is a method by which process (or program instances) can
exchange or pass data using an interface to a system-managed 2!e!e of messages. :essages can vary in
"ength and be assigned different types or usages. ( message queue can be created by one process and used
by mu"tip"e processes that read and7or write messages to the queue. /or examp"e, a ser3er process can read
and write messages from and to a message queue created for c"ient processes. !he message type can be
used to associate a message with a particu"ar c"ient process even though a"" messages are on the same
queue.
!he message queue is managed by the operating system (or kerne"). (pp"ication programs
(or their processes) create message queues and send and receive messages using an app"ication program
interface (API). In Uni4 systems, the C programming "anguage msgget function is used with various
parameters specifying the action requested, message queue I6, message type, and so forth.
!he maximum si3e of a message in a queue is "imited by the operating system and is typica""y
;,<=> bytes.
:essage queues a""ow one or more processes to write messages, which wi"" be read by one or
more reading processes. #inux maintains a "ist of message queues, the ms!"e vector2 each e"ement of
which points to a ms!id#ds data structure that fu""y describes the message queue. $hen message queues
are created a new ms!id#ds data structure is a""ocated from system memory and inserted into the vector.
ANA$O-.
Message 2!e!es? Information to be communicated is p"aced in a predefined message structure.
!he process generating the message specifies its type and p"aces the message in a system-maintained
message queue. Processes accessing the message queue can use the message type to se"ecti3e"y read
messages of specific types in a first in first out (/I/4) manner. :essage queues provide the user with a
means of asynchronous"y mu"tip"exing data from mu"tip"e processes.
O3er3iew
:essage queues provide an asynchrono!s comm!nications protoco", meaning that the sender and
receiver of the message do not need to interact with the message queue at the same time. :essages p"aced
onto the queue are stored unti" the recipient retrieves them.
:ost message queues have set "imits on the si3e of data that can be transmitted in a sing"e message. !hose
that do not have such "imits are %nown as mai"boxes. :any imp"ementations of message queues function
interna""y* within an operating system or within an app"ication. &uch queues exist for the purposes of that
system on"y.
4ther imp"ementations a""ow the passing of messages between different computer systems,
potentia""y connecting mu"tip"e app"ications and mu"tip"e operating systems. !hese message queueing
systems typica""y provide enhanced resi"ience functiona"ity to ensure that messages do not get @"ost@ in the
event of a system fai"ure.
USA-E5
In a typica" message-queueing imp"ementation, a system administrator insta""s and configures off-
the-she"f message-queueing software (a 2!e!e manager), and defines a named message queue. (n
app"ication then registers a software routine that @"istens@ for messages p"aced onto the queue. &econd and
subsequent app"ications may connect to the queue and transfer a message onto it. !he queue-manager
software stores the messages unti" a receiving app"ication connects and then ca""s the registered software
routine. !he receiving app"ication then processes the message in an appropriate manner...
!here are often numerous options as to the exact semantics of message passing, inc"uding*
$"ra%ilit& (e.g. - whether or not queued data can be mere"y %ept in memory, or if it mustn-t be "ost, and
thus must be stored on dis%, or, more expensive sti"", it must be committed more re"iab"y to a D%MS)
Security policies
'essae p"rin poli(ies - queues or messages may have a !!# (!ime !o #ive)
&ome systems support fi"tering data so that a subscriber may on"y see messages matching some pre-
specified criteria of interest
Delivery policies.
)o"tin poli(ies - in a system with many queue servers, what servers shou"d receive a message or a
queue-s messages5
Bat(hin poli(ies - shou"d messages be de"ivered immediate"y5 4r shou"d the system wait a bit and
try to de"iver many messages at once5
!hese are a"" considerations that can have substantia" effects on transaction semantics, system re"iabi"ity, and
system efficiency.
IMP$EMENTATION
:essage queues are one of the three different types of &ystem 1 IPC mechanisms. !his mechanism
enab"es processes to send information to each other asynchronous"y. !he word asynchronous in the present
context signifies that the sender process continues with its execution without waiting for the receiver to
receive or ac%now"edge the information. 4n the other side, the receiver does not wait if no messages are
there in the queue. !he queue being referred to here is the queue imp"emented and maintained by the %erne".
#et us now ta%e a "oo% at the system ca""s associated with this mechanism.
msgget5 !his, in a way simi"ar to shmget, gets a message queue identifier. !he format is
S.NTA6 5 int msgget(%et8t %ey, int msgf"g)2
!he first argument is a unique key, which can be generated by using ,tok a"gorithm. !he second argument is
the f"ag which can be IPC7CREAT, IPC7PRI8ATE, the permissions (read and7or write) are "ogica""y
4ed with the f"ags. msgget returns an identifier associated with the key. !his identifier can be used for
further processing of the message queue associated with the identifier.
msgct"5 !his contro"s the operations on the message queue. !he format is
S.NTA65 int msgct"(int msqid, int cmd, struct msqid8ds Abuf)2
,ere ms2id is the message queue identifier returned by msgget. !he second argument is cmd, which
indicates which action is to be ta%en on the message queue. !he third argument is a buffer of type str!ct
ms2id7ds. Bach message queue has this structure associated with it2 it is composed of records for queues to
be identified by the %erne". !his structure a"so defines the current status of the message queue. If one of the
cmds is IPC7SET, some fie"ds in the ms2id7ds structure (pointed by the third argument) wi"" be set to the
specified va"ues. &ee the man page for the detai"s.
msgsnd5 !his is for sending messages. !he format is
S.NTA65 int msgsnd(int msqid, struct msgbuf Amsgp, si3e8t msgs3, int msgf"g)2
!he first argument is the message queue identifier returned by msgget. !he second argument is a
structure that the ca""ing process a""ocates. ( ca"" to msgsnd appends a copy of the message pointed to by
msgp to the message queue identified by ms2id. !he third argument is the si3e of the message text within
the msg9!, structure. !he fourth argument is the f"ag that specify one of severa" actions to be ta%en as and
when a specific situation arises.
msgrc35 !his is for receiving messages. !he format is,
S.NTA65
ssi3e8t msgrcv(int msqid, struct msgbuf Amsgp, si3e8t msgs3, "ong msgtyp, int msgf"g)2
'esides the four arguments mentioned above for msgsnd, we a"so have msgtyp, which specifies the
type of message requested. &ee the man page for the options.
APP$ICATION
commercia" app"ication of this %ind of message queueing so,tware (a"so %nown as Message Oriented
Midd"eware) inc"ude I%M-s (e9Sphere M1 (former"y M1 Series), /iorano-s :C, Orac"e Ad3anced
1!e!ing ((C) within an Orac"e data9ase, and Microso,t-s MSM1. !here is a :a3a standard ca""ed :a3a
Message Ser3ice, which has, associated with it, a number of imp"ementations, both proprietary and open
source.
!here are a number of open source choices of messaging midd"eware systems, inc"uding :%oss Messaging,
:ORAM, Acti3eM1, Ra99itM1 (an imp"ementation, in Er"ang, of AM1P), ISectd, Skytoo"s Pg1 (runs
atop PostgreS1$, created by Skype).
:ost RTOSes, such as 84(orks and 1N6 operating systems encourage the use of message queueing as
the primary IPC or inter-thread communication mechanism. !he resu"ting tight integration between
message passing and CP+ schedu"ing is attributed as a main reason for the usabi"ity of !4&es for rea" time
app"ications. Bar"y examp"es of commercia" !4&es that encouraged a message-queue basis to inter-thread
communication a"so inc"ude 8RT6 and pSOSD, both of which date to the ear"y <=;Es.
E6 NO'; IPC USIN- S#ARED MEMOR. SE-MENT
AIM
!o imp"ement the concept of shared memory between the c"ient and the server process.
#ARD(ARE RE1UIREMENT
P- II FEE :,G speed, >EH' ,ard dis%, IF :' (:, J button mouse,
<EF %eys %eyboard, <F-inch co"or monitor.
SO/T(ARE RE1UIREMENT
#inux operating system
DESCRIPTION
&haring of the code or data is an advantage of segmentation. Bach process has a segment tab"e
associated with it, which the dispatcher uses to define the hardware segment tab"e when this process is
given the CP+. &egments are shared when entries in the segment tab"es of two different processes
point to the same physica" "ocation.
A$-ORIT#M
&tart the program.
In the server process, create a shared memory with the he"p of shmget() syetm ca"" then writs
the data on to the shared memory area.
In the c"ient process, create a shared memory with the he"p of shmget() system ca"" then data is
read from the shared memory segment content.
Print the resu"t.
&top the program.
PRO-RAM5 <Using Pipe=
K>itE=L"oca"host MNO vi pipe.c
Pinc"udeQstdio.hR
int main()
S
int fdK>N,ch2
char aK<EN2
printf(@TnBnter the string to enter into the pipe* @)2
scanf(@Us@,a)2
pipe(fd)2
chVfor%()2
if(Wch)
S
c"ose(fdKEN)2
write(fdK<N,a,X)2
wait(E)2
Y
e"se
S
c"ose(fdK<N)2
read(fdKEN,a,X)2
printf(@Tn!he string retrieved from the pipe is Us Tn@,a)2
Y
return E2
Y
OUTPUT5
K>itE=L"oca"host MNO cc pipe.c
K>itE=L"oca"host MNO .7a.out
Bnter the string to enter into the pipe* India
!he string retrieved from the pipe is India
PRO-RAM5 <Using Shared Memory=
K>itE=L"oca"host MNO vi shmem.c
Pinc"udeQstdio.hR
Pinc"udeQsys7shm.hR
Pinc"udeQsys7ipc.hR
int main()
S
int chi"d,shmid,i2
char Ashmptr2
chi"dVfor%()2
if(Wchi"d)
S
shmidVshmget(>EF<,J>,EIIIZIPC8CB(!)2
shmptrVshmat(shmid,E,E)2
printf(@TnParent waitingTn@)2
for(iVE2iQ>E2iDD)
S
shmptrKiNV-a-Di2
putchar(shmptrKiN)2
wait(.+##)2
Y
Y
e"se
S
shmidVshmget(>EF<,J>,EIII)2
shmptrVshmat(shmid,E,E)2
printf(@TnChi"d is readingTn@)2
for(iVE2iQ>E2iDD)
putchar(shmptrKiN)2
shmdt(.+##)2
shmct"(shmid,IPC8:I6,.+##)2
Y
return E2
Y
OUTPUT5
K>itE=L"oca"host MNO cc shmem.c
K>itE=L"oca"host MNO .7a.out
Parent waiting
abcdefghi0%"mnopqrst
Chi"d is reading
abcdefghi0%"mnopqrst
RESU$T5
!hus the concept of &hared :emory &egment [ pipes has been imp"emented.
PRODUCER > CONSUMER PRO%$EM
!he producer-consumer prob"em i""ustrates the need for synchroni3ation in systems where many
processes share a resource. In the prob"em, two processes share a fixed-si3e buffer. 4ne process produces
information and puts it in the buffer, whi"e the other process consumes information from the buffer. !hese
processes do not ta%e turns accessing the buffer, they both wor% concurrent"y. ,erein "ies the prob"em. $hat
happens if the producer tries to put an item into a fu"" buffer5 $hat happens if the consumer tries to ta%e an
item from an empty buffer5
In order to synchroni3e these processes, we wi"" b"oc% the producer when the buffer is fu"", and we wi""
b"oc% the consumer when the buffer is empty. &o the two processes, Producer and Consumer, shou"d wor%
as fo""ows*
(<) !he producer must first create a new widget.
(>) !hen, it chec%s to see if the buffer is fu"". If it is, the producer wi"" put itse"f to s"eep unti" the consumer
wa%es it up. ( @wa%eup@ wi"" come if the consumer finds the buffer empty.
(J) .ext, the producer puts the new widget in the buffer. If the producer goes to s"eep in step (>), it wi"" not
wa%e up unti" the buffer is empty, so the buffer wi"" never overf"ow. (F) !hen, the producer chec%s to see if
the buffer is empty. If it is, the producer assumes that the consumer is s"eeping, an so it wi"" wa%e the
consumer. 9eep in mind that between any of these steps, an interrupt might occur, a""owing the consumer to
run.
'uffer&i3e V J2
count V E2
Producer()
S
int widget2
$,I#B (true) S 77 "oop forever
ma%e8new(widget)2 77 create a new widget to put in the buffer
I/(countVV'uffer&i3e)
&"eep()2 77 if the buffer is fu"", s"eep
put8item(widget)2 77 put the item in the buffer
count V count D <2 77 increment count of items
I/ (countVV<)
$a%eup(Consumer)2 77 if the buffer was previous"y empty, wa%e
Y 77 the consumer
Y
(<) !he consumer chec%s to see if the buffer is empty. If so, the consumer wi"" put itse"f to s"eep unti" the
producer wa%es it up. ( @wa%eup@ wi"" occur if the producer finds the buffer empty after it puts an item into
the buffer.
(>) !hen, the consumer wi"" remove a widget from the buffer. !he consumer wi"" never try to remove a
widget from an empty buffer because it wi"" not wa%e up unti" the buffer is fu"".
(J) If the buffer was fu"" before it removed the widget, the consumer wi"" wa%e the producer.
(F) /ina""y, the consumer wi"" consume the widget. (s was the case with the producer, an interrupt cou"d
occur between any of these steps, a""owing the producer to run.
!he code might "oo% "i%e this*
Consumer()
S
int widget2
$,I#B(true) S 77 "oop forever
I/(countVVE)
&"eep()2 77 if the buffer is empty, s"eep
remove8item(widget)2 77 ta%e an item from the buffer
count V count D <2 77 decrement count of items
I/(countVV.-<)
$a%eup(Producer)2 77 if buffer was previous"y fu"", wa%e
77 the producer
Consume8item(widget)2 77 consume the item
Y
Y
E6'NO' ? PRODUCER CONSUMER PRO%$EM USIN- SEMAP#ORE
AIM5
!o create a producer consumer prob"em using semaphore.
#ARD(ARE RE1UIREMENT5
P-<FEE :,3 speed
IE :' (:
>F H' hard dis%
9eyboard
:ouse
:onitor
SO/T(ARE RE1UIREMENT5
#I.+\ 4perating &ystem
A$-ORIT#M5
&tart the Program.
6ec"are the variab"es as .8&B:(P,4B and &8&B:(P,4B
Hive the character as & and a"so if conditions
Print the critica" region and give the va"ues for semaphoreV<
Print the critica" region and give the va"ue for semaphoreVE
Bnd the program.
PRO-RAM5
K>itE=L"oca"host MNO vi prod.c
Pinc"udeQsys7ipc.hR
Pinc"udeQsys7types.hR
Pinc"udeQsys7sem.hR
Pinc"udeQstdio.hR
Pinc"udeQsys7msg.hR
Pdefine . <E
"ong smutex,sempty,sfu"",qid,mut,emp,fu""2
int wait (int)2
int signa"(int)2
void producer (void)2
void consumer (void)2
void print()2
struct sembuf sop2
main()
S
int ch2
smutex V semget((%ey8t)EA<>J,<,IPC8CB(!ZEIII)2
sempty V semget((%ey8t)EA<>F,<,IPC8CB(!ZEIII)2
sfu"" V semget((%ey8t)EA<>X,<,IPC8CB(!ZEIII)2
semct"(smutex,E,&B!1(#,<)2
semct"(sempty,E,&B!1(#,.)2
semct"(sfu"",E,&B!1(#,E)2
printf(@TnTtsmutex id is * Ud@,smutex)2
printf(@TnTtsempty id is * Ud@,sempty)2
printf(@TnTtsfu"" id is * Ud@,sfu"")2
qid V msgget((%ey8t)===,IPC8CB(!ZEIII)2
do
S
printf(@TnTt < * Producer@)2
printf(@TnTt >* Consumer@)2
printf(@TnTt J. Bxit@)2
printf(@TnTt Bnter ur Choice * @)2
scanf(@Ud@,[ch)2
if (ch VV<)
producer ()2
if(ch VV>)
consumer ()2
Y
whi"e (chWVJ)2
Y
int wait (int id)
S
if (idQE)
S
exit(E)2
Y
idVid -<2
return(id)2 Y
int signa"(int id)
S
idVidD<2
return (id)2
Y
void producer (void)
S
char itemK>EN2
empVwait (sempty)2
mutVwait(smutex)2
printf(@TnTt6urint $ait 4peration@)2
printf(@TnTtmutex va"ue is UdTn@,mut)2
printf(@TnTtempty va"ue is UdTn@,emp)2
printf(@TnTt producer in critica" section TnTt Bnter item *@)2
scanf(@Us@,item)2
if (msgsnd(qid,[item,>E,IPC8.4$(I!) VV -<)
printf(@TnTt:essage cou"d not be sent buffer fu""@)2
mutV signa" (smutex)2
fu"" V signa"(sfu"")2
printf(@TnTt6uring &igna" 4peration@)2
printf(@TnTtmutex va"ue is UdTn@,mut)2
printf(@TnTtfu"" va"ue is UdTn@,fu"")2Y
void consumer (void)
S
char itemK>EN2
fu""Vwait(sfu"")2
mutVwait(smutex)2
printf(@TnTt6uring wait 4peration@)2
printf(@TnTtmutex va"ue is UdTn@,mut)2
printf(@TnTtfu"" va"ue is UdTn@,fu"")2
printf(@TnTt Consumer in critica" section@)2
if (msgrcv(qid,[item,>E,E,IPC8.4$(I!) VV -<)
S
printf(@TnTt :essage cou"d not be received buffer empty@)2
exit(<)2
Y
printf(@TnTt :essage received * UsTn@, item)2
mut V signa" (smutex)2
emp V signa" (sempty)2
printf(@TnTt6uring &igna" 4peration@)2
printf(@TnTtmutex va"ue is UdTn@,mut)2
printf(@TnTtempty va"ue is UdTn@,emp)2
Y
OUTPUT5
K>itE=L"oca"host MNO cc prod.c
K>itE=L"oca"host MNO .7a.out
sumtex id is * =;JE]
sempty id is * <J<E]I
sfu"" id is * <IJ;FX
< * Producer
>* Consumer
J. Bxit
Bnter ur Choice * <
6urint $ait 4peration
mutex va"ue is =;JEI
empty va"ue is <J<E]X
producer in critica" section
Bnter item *hai
6uring &igna" 4peration
mutex va"ue is =;JE;
fu"" va"ue is <IJ;FI
< * Producer
>* Consumer
J. Bxit
Bnter ur Choice * >
6uring wait 4peration
mutex va"ue is =;JEI
fu"" va"ue is <IJ;FF
Consumer in critica" section
:essage received * hai
6uring &igna" 4peration
mutex va"ue is =;JE;
empty va"ue is <J<E]]
< * Producer
>* Consumer
J. Bxit
Bnter ur Choice *J
RESU$T 5
!hus the producer consumer prob"em using semaphore has been imp"emented.
C.C$E>III
MEMOR. A$$OCATION
&' PA-IN-
INTRODUCTION
Paging a""ocates memory in fixed-si3e chun%s ca""ed pages. ( bounds register is not
needed because a"" pages are the same si3e2 if you need "ess than a page the rest is wasted
(interna" fragmentation).
Bach process has a page tab"e that maps from the virtua" page to physica" page Page
tab"e can be "arge. (ssume J>-bit address space, F9' page, F bytes per page tab"e entry.
IMP$EMENTATION
,ow big is the page tab"e for each process5
&ay you have a P:(Physica" memory) of si3e <I9. ^ou can support a "arge number
of programs each of si3e say <:. Programs are provided with a virtua" address space (<:).
4& ta%es care of fetching the "ocation (from P: or from dis%). eg. "oad , K>E9N - !his is a
virtua" address programs thus wor% with virtua" addresses. It is the 4&- 0ob to find out where it
is and get the va"ue. !his is done by a mechanism ca""ed paging. 6ivide the entire virtua"
address space into units ca""ed pages. eg. for the < :', 1(&, you have >XI virtua" pages (E ...
>XX)
6ivide the physica" memory into pages. eg. for the <I9 physica" memory, you have F pages
(E .. J)
(t any time some (atmost F) of the virtua" pages cou"d be in one of the physica" pages. !he
rest are on the dis% in what is ca""ed the swap space.
( page is a"so the unit of transfer between the dis% (swap space) and physica"
memory.
^ou %eep trac% of which virtua" page is in physica" memory (if so where), and which
is not. !his information is maintained in a page tab"e. P! thus performs the mapping from
1((1irtua" (ddress) to P( (Physica" (ddress).
page tab"e (indexed by virtua" address) entry V .ote that this has to be done on every
reference (both data and code), which can turn out to be very cost"y to do by software.
+sua""y this is done by a hardware unit ca""ed the ::+ (which sits between the CP+ and the
cache).
Steps per,ormed 9y the MMU
Hiven a 1(, index into the P!(Page !ab"e) chec% if present, if so, put out phys
address on the bus and "et the memory operation be performed what do you do if absent5 you
have to go to dis% and get it. $e do not want to do this by hardware. &oftware shou"d gain
contro" at this point (access contro"). ,ardware raises a page fau"t. !his fau"t is caught by the
4&, the corresponding page is brought in from the dis% into a physica" page, the P! entry is
updated. In the process, a victim may need to be thrown out and its entry inva"idated.
Paging Iss!es
Page tab"es are #arge*
:apping :ust be /ast*
:a%e use of the "oca"ity in typica" executions*
&o"ution* !ransa"ation #oo%aside 'uffer
Page sie 3ers!s page ta9"e sie
( system with a sma""er page si3e uses more pages, requiring a page ta9"e that occupies more space.
/or examp"e, if a >
J>
virtua" address space is mapped to F9' (>
<>
bytes) pages, the number of virtua" pages
is >
>E
(>E V J> - <>). ,owever, if the page si3e is increased to J>9' (>
<X
bytes), on"y >
<]
pages are required.
Page sie 3ers!s T$% !sage
Processors need to maintain a Trans"ation $ookaside %!,,er (!#'), mapping virtua" to physica"
addresses, which are chec%ed on every memory access. !he !#' is typica""y of "imited si3e, and when it
cannot satisfy a given request (a !#' miss) the page ta9"es must be searched manua""y (either in hardware
or software, depending on the architecture) for the correct mapping, a time-consuming process. #arger page
si3es mean that a !#' cache of the same si3e can %eep trac% of "arger amounts of memory, which avoids the
cost"y !#' misses.
Interna" ,ragmentation o, pages
are"y do processes require the use of an exact number of pages. (s a resu"t, the "ast page wi"" "i%e"y
on"y be partia""y fu"", wasting some amount of memory. #arger page si3es c"ear"y increase the potentia" for
wasted memory this way, as more potentia""y unused portions of memory are "oaded into main memory.
&ma""er page si3es ensure a c"oser match to the actua" amount of memory required in an a""ocation.
(s an examp"e, assume the page si3e is <:'. If a process a""ocates <E>X9', two pages must be
used, resu"ting in <E>J9' of unused space.
Page sie 3ers!s disk access
$hen transferring from dis%, much of the de"ay is caused by the see% time. 'ecause of this, "arge,
sequentia" transfers are more efficient than severa" sma""er transfers. !ransferring "arger pages from dis% to
memory therefore, does not require much more time than sma""er pages.
Determining the page sie in a program
:ost operating systems a""ow programs to determine the page si3e at run time. !his a""ows programs
to use memory more efficient"y by a"igning a""ocations to this si3e and reducing overa"" interna"
fragmentation of pages.
/ragmentation o, the page ,i"e
4ccasiona""y, when the page fi"e is gradua""y expanded, it can become heavi"y ,ragmented and
cause performance prob"ems. !he common advice given to avoid this prob"em is to set a sing"e @"oc%ed@
page fi"e si3e so that $indows wi"" not resi3e it. 4ther peop"e be"ieve this to be prob"ematic in the case that
a $indows app"ication requests more memory than the tota" si3e of physica" and virtua" memory. In this
case, requests to a""ocate memory fai", which may cause the programs ma%ing the request (inc"uding system
processes) to crash. &upporters of this view wi"" note that the page fi"e is rare"y read or written in sequentia"
order, so the performance advantage of having a comp"ete"y sequentia" page fi"e is minima". ,owever, it is
genera""y agreed that a "arge page fi"e wi"" a""ow use of memory-heavy app"ications, and there is no pena"ty
except that more dis% space is used.
DE/RA-MENTATION
De,ragmenting the page fi"e is a"so occasiona""y recommended to improve performance when a
$indows system is chronica""y using much more memory than its tota" physica" memory. ("though this can
he"p s"ight"y, performance concerns are much more effective"y dea"t with by adding more physica" memory.
Advantages of Paging
.o externa" fragmentation
_ (ny page can be p"aced in any frame in physica" memory
_ /ast to a""ocate and free
` (""oc* .o searching for suitab"e free space
` /ree* 6oesn)t have to coa""esce with ad0acent free space
` aust use bitmap to show free7a""ocated page frames
&imp"e to swap-out portions of memory to dis%
_ Page si3e matches dis% b"oc% si3e
_ Can run process when some pages are on dis%
_ (dd bpresentc bit to P!B
Bnab"es sharing of portions of address space
_ !o share a page, have P!B point to same frame
Disadvantages of Paging
Interna" fragmentation* Page si3e may not match si3e
needed by process
_ $asted memory grows with "arger pages
_ !ension5
(dditiona" memory reference to "oo% up in page tab"e --R
1ery inefficient
_ Page tab"e must be stored imemory
_ ::+ stores on"y base address of page tab"e
&torage for page tab"es may be substantia"
_ &imp"e page tab"e* equires P!B for a"" pages in address space
` Bntry needed even if page not a""ocated
_ Prob"ematic with dynamic stac% and heap within address space
E6'NO'@a
MEMOR. MANA-EMENT AI
SIMU$ATION O/ PA-IN-
AIM5
!o write a program to simu"ate the paging.
#ARD(ARE RE1UIREMENT5
P-<FEE :,3 speed, IE :' (:, >F H' hard dis%, 9eyboard, :ouse, :onitor.
SO/T(ARE RE1UIREMENT5
#I.+\ 4perating &ystem
DESCRIPTION
Paging is a memory management scheme. It reduces the externa" fragmentation. :emory is
divided into fixed si3e b"oc%s ca""ed page frames. !he virtua" address space of a process is a"so sp"it
into fixed b"oc%s of the same si3e, ca""ed pages. !he si3e of the page frame is determined by the
hardware.
A$-ORIT#M5
&tart the Program.
ead the number of sequence.
ead the segno, base, and "imit va"ues for each segment.
ead the "ogica" address.
!he first digit in "ogica" address is the segno and ust is the offset.
If offsetQ"imit then for corresponding segno add offset and base va"ue, which is the
corresponding physica" address.
B"se print error message bP(HB /(+#!c.
&top the program.
PRO-RAM5
K>itE=L"oca"host MNO vi paging.c
Pinc"udeQstdio.hR
Pinc"udeQmath.hR
struct pagetab"e
S
int pno,fno2
YpK<EN2
char fKNV@ i0%"mnop abcdefgh@2
const int pgsi3eVF2
int "addr,pgno,offset,i,0,%,phyaddr,va"2
main()
S
printf(@Tn P(HB !('#B TnTn@)2
for(iVE2iQF2iDD)
S
pKiN.pnoViD<2
Y
pKEN.fnoVX2
pK<N.fnoVI2
pK>N.fnoV<2
pKJN.fnoV>2
printf(@TnP(HB.4 /(:B TnTn@)2
for(iVE2iQF2iDD)
printf(@Ud UdTn@,pKiN.pno,pKiN.fno)2
printf(@TnTn !he page si3e is UdTn@,pgsi3e)2
printf(@Tn #4HIC(# :B:4^TnTn@)2
%V=]2
for(iVE2iQ<I2iDD)
printf(@Ud UcTn@,iD<,%Di)2
printf(@TnTn B.!B !,B #4HIC(# (66B&&Tn@)2
scanf(@Ud@,["addr)2
iVE2
whi"e(<)
S if("addrQ<E) S
pgnoV"addr2
brea%2 Y
va"V<2
for(0VE20Qi20DD)
va"Vva"A<E2
offsetVoffsetD(("addrU<E)Ava")2
"addrV"addr7<E2
iDD2 Y
if(offsetQpgsi3e)
S %VE2
for(iVE2iQF2iDD)
S if(pgnoVVpKiN.pno)
S phyaddrV(pKiN.fnoApgsi3e)Doffset2
printf(@Tn !he contents in the equa"ent@)2
printf(@Tn physica" address is Uc Tn@,fKphyaddrN)2
%V<2
brea%2
Y Y Y
e"se
printf(@TnTn page fau"tTn@)2
if(%VVE)
printf(@TnTn P(HB /(+#! Tn@)2
Y
OUTPUT5
K>itE=L"oca"host MNO cc paging.c
K>itE=L"oca"host MNO .7a.out
P(HB !('#B
P(HB.4 /(:B
< X
> I
J <
F >
!he page si3e is F
#4HIC(# :B:4^
< a
> b
J c
F d
X e
I f
] g
; h
= i
<E 0
<< %
<> "
<J m
<F n
<X o
<I p
B.!B !,B #4HIC(# (66B&&
JJ
!he contents in the equa"ent
physica" address is n
RESU$T5
!hus the simu"ation of paging has been deve"oped .
0'SE-MENTATION
&egmentation is one of the most common ways to achieve memory protection2 another common
one is paging.
In a computer system using segmentation, an instruction operand that refers to a memory "ocation
inc"udes a va"ue that identifies a segment and an offset within that segment. ( segment has a set of
permissions, and a "ength, associated with it. If the current"y running process is a""owed by the permissions
to ma%e the type of reference to memory that it is attempting to ma%e, and the offset within the segment is
within the range specified by the "ength of the segment, the reference is permitted2 otherwise, a hardware
e4ception is de"ivered.
In addition to the set of permissions and "ength, a segment a"so has associated with it information
indicating where the segment is "ocated in memory. It may a"so have a f"ag indicating whether the segment
is present in main memory or not2 if the segment is not present in main memory, an exception is de"ivered,
and the operating system wi"" read the segment into memory from secondary storage. !he information
indicating where the segment is "ocated in memory might be the address of the first "ocation in the segment,
or might be the address of a page ta9"e for the segment.
In the first case, if a reference to a "ocation within a segment is made, the offset within the segment
wi"" be added to address of the first "ocation in the segment to give the address in memory of the referred-to
item2 in the second case, the offset of the segment is trans"ated to a memory address using the page tab"e.
IMP$EMENTATION
Programmer)s view of memory is not usua""y as a sing"e "inear address space
Programmer doesn)t %now how "arge these wi"" be, or how they)"" grow, and doesn)t want to manage
where they go in virtua" memory.
SE-MENTATION (IT# PA-IN-
Simi"arity5
(ddress space can exceed si3e of rea" memory.
Di,,erences5
Programmer is aware of segmentation. Paging is hidden.
&egmentation maintains multiple address spaces per process.
Paging maintains one address space.
&egmentation a""ows procedures and data to be separately protected. !his is hard with paging.
&egmentation easi"y permits tab"es whose si3e varies.
&egmentation facilitates sharing of procedures between processes. !his is hard with paging.
Pure segmentation suffers from memory fragmentation.
&egmentation and Paging can be used together.
Programmer is aware of segments.
Hains a"" the protection and sharing benefits.
$ithin each segment, paging is used.
(voids externa" memory fragmentation
+ses memory efficient"y.
Ad3antages o, Segmentation
(dvantages of &egments
_ &upports sparse address spaces
` 6ecreases si3e of page tab"es
` If segment not used, not need for page tab"e
(dvantages of Pages
_ .o externa" fragmentation
_ &egments can grow without any reshuff"ing
_ Can run process when some pages are swapped to dis%
(dvantages of 'oth
_ Increases f"exibi"ity of sharing ` &hare either sing"e page or entire segment and ,ow5
Disad3antages o, Segmentation
4verhead of accessing memory
_ Page tab"es reside in main memory
_ 4verhead reference for every rea" memory
reference
#arge page tab"es
_ :ust a""ocate page tab"es contiguous"y
_ :ore prob"ematic with more address bits
_ Page tab"e si3e5
` (ssume > bits for segment, <; bits for page number, <> bits for offset
E6'NO'@9 SIMU$ATION O/ SE-MENTATION
AIM5
!o write a program to simu"ate segmentation.
#ARD(ARE RE1UIREMENT5
P- <<FEE :,G speed, >EH' ,ard dis%, IF :' (:, J button mouse,
<EF %eys %eyboard, <F-inch co"or monitor.
SO/T(ARE RE1UIREMENT5
#inux operating system.
DESCRIPTION5
&egmentation is a memory management scheme. It divides a program into a number of sma""er
b"oc%s ca""ed segments. ( segment can be defined as a "ogica" grouping of information, such as a
subroutine, array or data area. &egmentation is variab"e si3e. ( "ogica" address using segmentation
consists of two parts* a segment number and an offset. &egmentation is simi"ar to dynamic partitioning
because of the unequa" si3e segments. It e"iminates interna" fragmentation but it suffers from externa"
fragmentation.
A$-ORIT#M5
&tart the program.
ead the number of segments.
ead the segno, base, "imit va"ues for each segment.
ead the "ogica" address.
!he first digit in "ogica" address is the segno and rest is the offset.
If offset Q "imit then for corresponding segno add offset and base va"ue.
B"se print error message as bP(HB /(+#!c.
&top the program.
PRO-RAM5
K>itE=L"oca"host MNO vi segment.c
Pinc"udeQstdio.hR
Pinc"udeQmath.hR
struct seg
S
int segno,base,"ength2
YsegK<EN2
main()
S
int n,va",i,0,offset,%2
int segno,"addr2
printf(@Tn Bnter the no.of segments*Tn@)2
scanf(@Ud@,[n)2
for(iVE2iQn2iDD)
S
printf(@Tn Bnter the segno(non E),base,"imit for each segment*Tn@)2
scanf(@UdUdUd@,[segKiN.segno,[segKiN.base,[segKiN."ength)2
Y
printf(@Tn Bnter the "ogica" address Tn@)2
scanf(@Ud@,["addr)2
offsetVE2
iVE2
whi"e(<)
S
if("addrQ<E)
S
segnoV"addr2
brea%2
Y
va"V<2
for(0QE20Qi20DD)
va"Vva"A<E2
offsetVoffsetD("addrU<E)Ava"2
"addrV"addr7<E2
iDD2
Y
%V<2
for(iVE2iQn2iDD)
if((segKiN."engthRoffset)[[(segKiN.segnoVVsegno))
S
%VE2
printf(@Tn !he physica" address is UdTn@,(segKiN.baseDoffset))2
brea%2
Y
if(%VV<)
printf(@Tn P(HB /(+#! Tn@)2
Y
OUTPUT5
K>itE=L"oca"host MNO cc segment.c
K>itE=L"oca"host MNO .7a.out
Bnter the no.of segments*
F
Bnter the segno(non E),base,"imit for each segment*
< >JEE <F
Bnter the segno(non E),base,"imit for each segment*
> =E <EE
Bnter the segno(non E),base,"imit for each segment*
J <J>] X;E
Bnter the segno(non E),base,"imit for each segment*
F <=X> =I
Bnter the "ogica" address
<<E
!he physica" address is >J<E
RESU$T5
!hus the simu"ation of segmentation has been deve"oped.
/IRST SITB %EST /ITB (ORST /IT
INTRODUCTION
!he rea" cha""enge of efficient"y managing memory is seen in the case of a system which has
mu"tip"e processes running at the same time. &ince primary memory can be space-mu"tip"exed, the memory
manager can a""ocate a portion of primary memory to each process for its own use. ,owever, the memory
manager must %eep trac% of which processes are running in which memory "ocations, and it must a"so
determine how to a""ocate and dea""ocate avai"ab"e memory when new processes are created and when o"d
processes comp"ete execution. $hi"e various different strategies are used to a""ocate space to processes
competing for memory, three of the most popu"ar are 'est fit, $orst fit, and /irst fit.
%est ,it5 !he a""ocator p"aces a process in the sma""est b"oc% of una""ocated memory in which it wi"" fit.
/or examp"e, suppose a process requests <>9' of memory and the memory manager current"y has a "ist of
una""ocated b"oc%s of I9', <F9', <=9', <<9', and <J9' b"oc%s. !he best-fit strategy wi"" a""ocate <>9'
of the <J9' b"oc% to the process.
(orst ,it5 !he memory manager p"aces a process in the "argest b"oc% of una""ocated memory avai"ab"e.
!he idea is that this p"acement wi"" create the "argest ho"d after the a""ocations, thus increasing the
possibi"ity that, compared to best fit, another process can use the remaining space. +sing the same examp"e
as above, worst fit wi"" a""ocate <>9' of the <=9' b"oc% to the process, "eaving a ]9' b"oc% for future use.
/irst ,it5 !here may be many ho"es in the memory, so the operating system, to reduce the amount of time it
spends ana"y3ing the avai"ab"e spaces, begins at the start of primary memory and a""ocates memory from the
first ho"e it encounters "arge enough to satisfy the request. +sing the same examp"e as above, first fit wi""
a""ocate <>9' of the <F9' b"oc% to the process.
%ASIC RE1UIREMENTS5
'asic requirements that drive memory designs
!he primary memory access time must be as sma"" as possib"e. !his need inf"unences both software
and hardware design
!he primary memory must be as "arge as possib"e. +sing virtua" memory, software and hardware can
ma%e the memory appear to be "arger than it actua""y is
!he primary memory must be cost-effective. !he cost cannot be more than a sma"" percentage of the
tota" cost of the computer.
Primary
:emory
'est fit $orst fit /irst fit
.otice in the diagram above that the 'est fit and /irst fit strategies both "eave a tiny segment of memory
una""ocated 0ust beyond the new process. &ince the amount of memory is sma"", it is not "i%e"y that any new
processes can be "oaded here. !his condition of sp"itting primary memory into segments as the memory is
a""ocated and dea""ocated is %nown as fragmentation. !he $orst fit strategy attempts to reduce the prob"em
of fragmentation by a""ocating the "argest fragments to new processes. !hus, a "arger amount of space wi""
be "eft as seen in the diagram above.
Memory Manager
@!he memory manager is responsib"e for a""ocating primary memory to processes and for assisting the
programmer in "oading and storing the contents of the primary memory. :anaging the sharing of primary
memory and minimi3ing memory access time are the basic goa"s of the memory manager.@
!he purpose of the memory manager is
to a""ocate primary memory space to processes
to mao the process address space into the a""ocated portion of the primary memory
to minimi3e access times using a cost-effective amount of primary memory
Memory Management A"gorithms
In an environment that supports dynamic memory a""ocation, the memory manager must %eep a record of
the usage of each a""ocatab"e b"oc% of memory. !his record cou"d be %ept by using a"most any data structure
that imp"ements "in%ed "ists. (n obvious imp"ementation is to define a free "ist of b"oc% descriptors, with
each descriport containing a pointer to the next descriptor, a pointer to the b"oc%, and the "ength of the b"oc%.
!he memory manager %eeps a free "ist pointer and inserts entries into the "ist in some order conducive to its
a""ocation strategy. ( number of strategies are used to a""ocate space to the processes that are competing for
memory.
%est /it
!he a""ocator p"aces a process in the sma""est b"oc% of una""ocated memory in which it wi"" fit.
Problems:
It requires an expensive search of the entire free "ist to find the best ho"e.
:ore important"y, it "eads to the creation of "ots of "itt"e ho"es that are not big enough to satisfy any requests.
!his situation is ca""ed fragmentationB and is a prob"em for a"" memory-management strategies, a"though it
is particu"ar"y bad for best-fit.
Solution: 4ne way to avoid ma%ing "itt"e ho"es is to give the c"ient a bigger b"oc% than it as%ed for. /or
examp"e, we might round a"" requests up to the next "arger mu"tip"e of IF bytes. !hat doesn-t ma%e the
fragmentation go away, it 0ust hides it.
(orst /it
!he memory manager p"aces process in the "argest b"oc% of una""ocated memory avai"ab"e. !he ides is that
this p"acement wi"" create the "argest ho"e after the a""ocations, thus increasing the possibi"ity that, compared
to best fit, another process can use the ho"e created as a resu"t of externa" fragmentation.
/irst /it
(nother strategy is first fit, which simp"y scans the free "ist unti" a "arge enough ho"e is found.
6espite the name, first-fit is genera""y better than best-fit because it "eads to "ess fragmentation.
Problems5
&ma"" ho"es tend to accumu"ate near the beginning of the free "ist, ma%ing the memory a""ocator search
farther and farther each time.
Solution: .ext /it- !his /it is a variant of the first-fit strategy.!he prob"em of sma"" ho"es accumu"ating is
so"ved with next fit a"gorithm, which starts each search where the "ast one "eft off, wrapping around to the
beginning when the end of the "ist is reached (a form of one-way e"evator)
COMPACTION
Compaction attac%s the prob"em of fragmentation by moving a"" the a""ocated b"oc%s to one end of
memory, thus combining a"" the ho"es. (side from the obvious cost of a"" that copying, there is an important
"imitation to compaction* (ny pointers to a b"oc% need to be updated when the b"oc% is moved. +n"ess it is
possib"e to find a"" such pointers, compaction is not possib"e. Pointers can stored in the a""ocated b"oc%s
themse"ves as we"" as other p"aces in the c"ient of the memory manager. In some situations, pointers can
point not on"y to the start of b"oc%s but a"so into their bodies. /or examp"e, if a b"oc% contains executab"e
code, a branch instruction might be a pointer to another "ocation in the same b"oc%. Compaction is
performed in three phases. /irst, the new "ocation of each b"oc% is ca"cu"ated to determine the distance the
b"oc% wi"" be moved. !hen each pointer is updated by adding to it the amount that the b"oc% it is pointing
(in)to wi"" be moved. /ina""y, the data is actua""y moved. !here are various c"ever tric%s possib"e to combine
these operations.
E6'NO'Ca
MEMOR. MANA-EMENT AII
/IRST /IT
AIM5
!o write a program for first fit.
#ARD(ARE RE1UIREMENT5
P- <<FEE :,G speed
>EH' ,ard dis%
IF :' (:
J button mouse
<EF %eys %eyboard
<F-inch co"or monitor
SO/T(ARE RE1UIREMENT5
#inux operating system.
DESCRIPTION5
!he a""ocator p"aces a process in the sma""est b"oc% of una""ocated memory in which it wi"" fit. /or
examp"e, suppose a process requests <>9' of memory and the memory manager current"y has a "ist of
una""ocated b"oc%s of I9', <F9', <=9', <<9', and <J9' b"oc%s. !he best-fit strategy wi"" a""ocate
<>9' of the <J9' b"oc% to the process.
/irst fit chooses the b"oc% that is avai"ab"e first in the "ist for the request. It a""ocates the first ho"e
(b"oc%) irrespective of its si3e. It is the most popu"ar a"gorithm for dynamic memory a""ocation. !his
a"gorithm suffers from externa" fragmentation.
A$-ORIT#M5
&tart the program.
6ec"are the variab"es such as interna", externa", no. of pages, no. of prog, a""ocating si3e.
Hive the va"ues for interna" and externa".
Ca"cu"ate the va"ues for temp as we"" as se"ect page.
Ca"cu"ate the no. of pages for each page.
Print the interna" fragmentation and externa" fragmentation.
&top the program.
PRO-RAM5
K>itE=L"oca"host MNO vi ffit.c
Pinc"udeQstdio.hR
Pinc"udeQstring.hR
Pinc"udeQmath.hR
struct segment
S
char 0obidK<EN2
int si3e2
char statusK<EN2
YsK<EN2
char programidK>ENK>EN2
int n,t,v,pos,i,0,progsi3eK<EN,va",ch2
int tota"memVE,maxmemVE,snVE2
main()
S system(@c"ear@)2
menu()2
for(0VE20Qn20DD)
S snVE2
for(iVE2iQ<E2iDD)
S if((progsi3eK0NQVsKiN.si3e)[[ W(strcmp(sKiN.status,@/BB@)))
S strcpy(sKiN.0obid,programidK0N)2
strcpy(sKiN.status,@4CC+PIB6@)2
snV<2
brea%2 Y Y
if(snVVE)
S printf(@Us has no space@, programidK0N)2 Y Y
printf(@Tn Tt a4' I6 Tt Tt &IGB TtTt &!(!+&Tn@)2
for(iVE2iQ<E2iDD)
printf(@Tt Us TtTt Ud TtTt UsTn @,sKiN.0obid, sKiN.si3e, sKiN.status)2 Y
menu()
S for(iVE2iQ<E2iDD)
S va"Vrand()U<EE2
if(va"VVE)
sKiN.si3eVrand()U;E2
e"se
sKiN.si3eVva"2
tota"memDVsKiN.si3e2
if(sKiN.si3eRmaxmem)
maxmemVsKiN.si3e2
strcpy(sKiN.0obid,@.+##@)2
strcpy(sKiN.status,@/BB@)2
printf(@Tn Tt Us TtTtUdTtTtUs@,sKiN.0obid,sKiN.si3e,sKiN.status)2 Y
printf(@Tn Tn !ota" memory spaceUdTt@, tota"mem)2
printf(@Tn :aximum si3e* UdTt@, maxmem)2
printf(@Tn Bnter no of 0obs you want to storeTn@)2
scanf(@Ud@,[n)2
for(iVE2iQn2iDD)
S printf(@Tn Bnter the program id*Tn@)2
scanf(@Us@,programidKiN)2
printf(@Tn Bnter the si3e of the programTn@)2
scanf(@Ud@,[progsi3eKiN)2
if(maxmemQprogsi3eKiN)
S printf(@Tt Tt &ufficient :emory Ud, Bnter again*@, maxmem)2
scanf(@Ud@,[progsi3eKiN)2 Y Y Y
OUTPUT5
K>itE=L"oca"host MNO cc ffit.c
K>itE=L"oca"host MNO .7a.out
.+## ;J /BB
.+## ;I /BB
.+## ]] /BB
.+## <X /BB
.+## =J /BB
.+## JX /BB
.+## ;I /BB
.+## => /BB
.+## F= /BB
.+## >< /BB
!ota"memoryspaceIJ]
:aximum si3e* =J
Bnter no of 0obs you want to store
>
Bnter the program id*
p<
Bnter the si3e of the program
>E
Bnter the program id*
p>
Bnter the si3e of the program
;E
a4' I6 &IGB &!(!+&
p< ;J 4CC+PIB6
p> ;I 4CC+PIB6
.+## ]] /BB
.+## <X /BB
.+## =J /BB
.+## JX /BB
.+## ;I /BB
.+## => /BB
.+## F= /BB
.+## >< /BB
RESU$T5
!hus the program for first fit has been executed.
E6'NO'C9 %EST /IT
AIM5
!o write a program for best fit.
#ARD(ARE RE1UIREMENT5
P- <<FEE :,G speed
>EH' ,ard dis%
IF :' (:
J button mouse
<EF %eys %eyboard
<F-inch co"or monitor
SO/T(ARE RE1UIREMENT5
#inux operating system.
DESCRIPTION5
'est fit chooses the b"oc% that is c"osest in si3e to the request. It a""ocates the sma""est ho"e
(b"oc%) that is big enough. It is the most popu"ar a"gorithm for dynamic memory a""ocation. It searches
the entire free "ist to find the sma""est free b"oc% "arge enough. !his a"gorithm suffers from externa"
fragmentation.
A$-ORIT#M5
&tart the program.
6ec"are the variab"es such as interna", externa", no. of pages, no. of prog, a""ocating si3e.
Hive the va"ues for interna" and externa".
Ca"cu"ate the va"ues for temp as we"" as se"ect page.
Ca"cu"ate the no. of pages for each page.
Print the interna" fragmentation and externa" fragmentation.
&top the program.
PRO-RAM5
K>itE=L"oca"host MNO vi bestfit.c
Pinc"udeQstdio.hR
Pinc"udeQstring.hR
Pinc"udeQmath.hR
struct segment
S
char 0obidK<EN2
int si3e2
char statusK<EN2
YsK<EN2
char programidK>ENK>EN2
int n,t,v,pos,i,0,progsi3eK<EN,va",ch2
int tota"memVE,maxmemVE,snVE2
main()
S
system(@c"ear@)2
menu()2
for(iVE2iQ<E2iDD)
S for(0ViD<20Q<E20DD)
S if(sKiN.si3eRsK0N.si3e)
S tVsKiN.si3e2
sKiN.si3eVsK0N.si3e2
sK0N.si3eVt2
Y Y Y
for(0VE20Qn20DD)
S snVE2
for(iVE2iQ<E2iDD)
S if((sKiN.si3eRVprogsi3eK0N)[[W(strcmp(sKiN.status,@/BB@)))
S strcpy(sKiN.0obid,programidK0N)2
strcpy(sKiN.status,@4CC+PIB6@)2
snV<2
brea%2 Y Y
if(snVVE)
S printf(@Us has no space@,programidK0N)2 Y Y
printf(@Tn Tt a4' I6 Tt Tt &IGB Tt Tt &!(!+&Tn@)2
for(iVE2iQ<E2iDD)
printf(@Tt Us Tt Tt Ud Tt Tt Us Tn@, sKiN.0obid,sKiN.si3e,sKiN.status)2 Y
menu()
S for(iVE2iQ<E2iDD)
S va"Vrand()U<EE2
if(va"VVE)
sKiN.si3eVrand()U;E2
e"se
sKiN.si3eVva"2
tota"memDVsKiN.si3e2
if(sKiN.si3eRmaxmem)
maxmemVsKiN.si3e2
strcpy(sKiN.0obid,@.+##@)2
strcpy(sKiN.status,@/BB@)2
printf(@Tn Tt Us TtTtUdTtTtUs@,sKiN.0obid,sKiN.si3e,sKiN.status)2 Y
printf(@Tn Tn !ota" memory spaceUdTt@, tota"mem)2
printf(@Tn :aximum si3e* UdTt@, maxmem)2
printf(@Tn Bnter no of 0obs you want to storeTn@)2
scanf(@Ud@,[n)2
for(iVE2iQn2iDD)
S printf(@Tn Bnter the program id*Tn@)2
scanf(@Us@,programidKiN)2
printf(@Tn Bnter the si3e of the programTn@)2
scanf(@Ud@,[progsi3eKiN)2
if(maxmemQprogsi3eKiN)
S printf(@Tt Tt &ufficient :emory Ud, Bnter again*@, maxmem)2
scanf(@Ud@,[progsi3eKiN)2 Y Y Y
OUTPUT5
K>itE=L"oca"host MNO cc bestfit.c
K>itE=L"oca"host MNO .7a.out
.+## ;J /BB
.+## ;I /BB
.+## ]] /BB
.+## <X /BB
.+## =J /BB
.+## JX /BB
.+## ;I /BB
.+## => /BB
.+## F= /BB
.+## >< /BB
!ota" memory spaceIJ]
:aximum si3e* =J
Bnter no of 0obs you want to store >
Bnter the program id* p<
Bnter the si3e of the program <F
Bnter the program id* p>
Bnter the si3e of the program F;
a4' I6 &IGB &!(!+&
p< <X 4CC+PIB6
.+## >< /BB
.+## JX /BB
p> F= 4CC+PIB6
.+## ]] /BB
.+## ;J /BB
.+## ;I /BB
.+## ;I /BB
.+## => /BB
.+## =J /BB
RESU$T5
!hus the program for best fit has been executed.
E6'NO'Cc
(ORST /IT
AIM5
!o write a program for worst fit.
.
#ARD(ARE RE1UIREMENT5
P- <<FEE :,G speed
>EH' ,ard dis%
IF :' (:
J button mouse
<EF %eys %eyboard
<F-inch co"or monitor
SO/T(ARE RE1UIREMENT5
#inux operating system.
DESCRIPTION5
$orst fit a""ocates the "argest ho"e. It searches the entire "ist. It reduces the rate of production
of sma"" ho"e. !his a"gorithm suffers from externa" fragmentation.
A$-ORIT#M5
&tart the program.
6ec"are the variab"es such as interna", externa", no. of pages, no. of prog, a""ocating si3e.
Hive the va"ues for interna" and externa".
Ca"cu"ate the va"ues for temp as we"" as se"ect page.
Ca"cu"ate the no. of pages for each page.
Print the interna" fragmentation and externa" fragmentation.
&top the program.
PRO-RAM5
K>itE=L"oca"host MNO vi worstfit.c
Pinc"udeQstdio.hR
Pinc"udeQstring.hR
Pinc"udeQmath.hR
struct segment
S
char 0obidK<EN2
int si3e2
char statK<EN2
Y
sK<EN2
char progidK>ENK>EN2
int n,t,v,pos,i,0,progsi3eK<EN,va",ch2
int tota"memVE,maxmemVE,snVE2
main()
S
system(@c"ear@)2
menu()2
for(iVE2iQ<E2iDD)
S
for(0VE20Q<E20DD)
S
if(sKiN.si3eRsK0N.si3e)
S
tVsKiN.si3e2
sKiN.si3eVsK0N.si3e2
sK0N.si3eVt2
Y
Y
Y
for(0VE20Qn20DD)
S
snVE2
for(iVE2iQ<E2iDD)
S
strcpy(sKiN.0obid,progidK0N)2
strcpy(sKiN.stat,@4CC+PIB6@)2
snV<2
brea%2
Y
if(snVVE)
S
printf(@Us has no space@,progidK0N)2
Y
Y
printf(@TnTt'"oc%TtaobidTt&i3eTtTt&tatusTn@)2
for(iVE2iQ<E2iDD)
printf(@TtUdTtUsTtTtUdTtTtUsTn@,i,sKiN.0obid,sKiN.si3e,sKiN.stat)2
Y
menu()
S
for(iVE2iQ<E2iDD)
S
va"Vrand()U<EE2
if(va"VVE)
sKiN.si3eVrand()U;E2
e"se
sKiN.si3eVva"2
tota"memDVsKiN.si3e2
if(sKiN.si3eRmaxmem)
maxmemVsKiN.si3e2
strcpy(sKiN.0obid,@.+##@)2
strcpy(sKiN.stat,@/BB@)2
printf(@TnTtUsTtTtUdTtTtUs@,sKiN.0obid,sKiN.si3e,sKiN.stat)2
Y
printf(@TnTn!ota" memeory space UdTt@,tota"mem)2
printf(@Tn:aximum si3e Ud Tt @,maxmem)2
printf(@TnBnter the no. of 0obs you want to store * Tn@)2
scanf(@Ud@,[n)2
for(iVE2iQn2iDD)
S
printf(@TnBnter the program id*Tn@)2
scanf(@Us@,progidKiN)2
printf(@Bnter si3e of program*Tn@)2
scanf(@Ud@,[progsi3eKiN)2
if(maxmemQprogsi3eKiN)
S
printf(@TtTt&ufficient memory Ud,Bnter again@,maxmem)2
Y
Y
Y
OUTPUT5
K>itE=L"oca"host MNO cc worstfit.c
K>itE=L"oca"host MNO .7a.out
.+## ;J /BB
.+## ;I /BB
.+## ]] /BB
.+## <X /BB
.+## =J /BB
.+## JX /BB
.+## ;I /BB
.+## => /BB
.+## F= /BB
.+## >< /BB
!ota" memeory space IJ]
:aximum si3e =J
Bnter the no. of 0obs you want to store *
<
Bnter the program id*
(
Bnter si3e of program*
>F
'"oc% aobid &i3e &tatus
E ( =J 4CC+PIB6
< .+## => /BB
> .+## ;I /BB
J .+## ;I /BB
F .+## ;J /BB
X .+## ]] /BB
I .+## F= /BB
] .+## JX /BB
; .+## >< /BB
= .+## <X /BB
RESU$T5
!hus the program for worst fit has been executed.
/I$E S.STEM
/i"e>System Str!ct!re
/i"e structure
#ogica" storage unit
Co""ection of re"ated information
/i"e system resides on secondary storage (dis%s)
/i"e system organi3ed into "ayers
/i"e contro" b"oc% ` storage structure consisting of information about a fi"e
$ayered /i"e System
A Typica" /i"e Contro" %"ock
$inked A""ocation
Bach fi"e is a "in%ed "ist of dis% b"oc%s* b"oc%s may be scattered anywhere on the dis%.
pointer
block
=
&imp"e ` need on"y starting address
/ree-space management system ` no waste of space
.o random access
:apping
'"oc% to be accessed is the Cth b"oc% in the "in%ed chain of b"oc%s representing the fi"e.
6isp"acement into b"oc% V D <
/i"e-a""ocation tab"e (/(!) ` dis%-space a""ocation used by :&-64& and 4&7>.
$inked A""ocation
$ADE&&
1
R
/i"e>A""ocation Ta9"e
Re"ated Ur"Fs
<.www.goog"e.com
>.www.wi%ipedia.com
J.www.unix"ibrary.com
E6'NO'&G
/I$E A$$OCATION TEC#NI1UE <$INHED=
AIM5
!o write a program for imp"ementing "in%ed fi"e a""ocation technique.
#ARD(ARE RE1UIREMENT5
P- <<FEE :,G speed
>EH' ,ard dis%
IF :' (:
J button mouse
<EF %eys %eyboard
<F-inch co"or monitor
SO/T(ARE RE1UIREMENT5
#inux operating system.
A$-ORIT#M5
&tart the program.
6ec"are the variab"es such as interna", externa", no. of pages, no. of prog, a""ocating si3e.
Hive the va"ues for interna" and externa".
Ca"cu"ate the va"ues for temp as we"" as se"ect page.
Ca"cu"ate the no. of pages for each page.
Print the interna" fragmentation and externa" fragmentation.
&top the program.
PRO-RAM5
K>itE=L"oca"host MNO vi fat.c
Pinc"udeQstdio.hR
main()
S
int n,bK<EN,aV<,eVE2
char fnK<EN2
int s,i,"2
printf(@Bnter no. of b"oc%(Q<E)@)2
scanf(@Ud@,[n)2
for(iVE2iQn2iDD)
S
bKiNVe2
printf(@Tn'"oc% UdVUd@,i,bKiN)2
Y
printf(@Tn Bnter the fi"e name,starting b"oc%,"ength of fi"e*@)2
scanf(@UsUdUd@,fn,[s,[")2
for(iVs2iQV(sD"-<)2iDD)
S
bKiNVa2
Y
printf(@Tn(fter a""ocation@)2
for(iVE2iQn2iDD)
S
if(bKiNVVe)
printf(@Tn'"oc% UdVUd@,i,bKiN)2
e"se
printf(@Tn'"oc% UdVUd@,i,bKiN)2
Y
Y
OUTPUT5
K>itE=L"oca"host MNO cc fat.c
K>itE=L"oca"host MNO .7a.out
Bnter no. of b"oc%(Q<E)I
'"oc% EVE
'"oc% <VE
'"oc% >VE
'"oc% JVE
'"oc% FVE
'"oc% XVE
Bnter the fi"e name,starting b"oc%,"ength of fi"e*
4perating
J
X
(fter a""ocation
'"oc% EVE
'"oc% <VE
'"oc% >VE
'"oc% JV<
'"oc% FV<
'"oc% XV<
RESU$T5
!hus the program for imp"ementing "in%ed fi"e a""ocation technique has been executed.