Sie sind auf Seite 1von 65

Interprocess Interprocess

Communication Communication
IPC Fundamentals :
What is IPC?
-Mechanisms to transfer data between processes.
Why IPC?
- Networ !pplications demand transfer of data across
two processes either on same or different machine.
-Comple" applications are difficult to build usin# sin#le -Comple" applications are difficult to build usin# sin#le
process.
-Multitasin# $% pro&ides facilities to run multiple
process. 'these need some way of communication(
Why processes communicate?
) *o share resources
) Client+ser&er paradi#ms
) Inherently distributed applications
) ,eusable software components
*wo Forms of IPC:
IPC from the $% Point of -iew:
Private
address
space
Private
address
space
OS address space
Process A
Process B
space
space
Fundamental IPC Problem for the $%:
-.ach process has a pri&ate address space.
-Normally/ no process can write to another process0s space
-1ow to #et important data from process ! to process 2?
$% %olutions to IPC Problem: $% %olutions to IPC Problem:
Fundamentally/ two options:
3. %upport some form of shared address space %hared
memory
4. 5se $% mechanisms to transport data from one address
space to another
- Files/ messa#es/ pipes/ ,PC
IPC is used for 4 functions:
3( %ynchroni6ation7
-5sed to coordinate access to resources amon# processes
and also to coordinate the e"ecution of these
processes.
*hey are ,ecord locin#/ %emaphores/ Mute"es and *hey are ,ecord locin#/ %emaphores/ Mute"es and
Condition &ariables.
4( Messa#e Passin#7
-5sed when processes wish to e"chan#e information.
Messa#e passin# taes se&eral forms such as :
Pipes/
FIF$s/
Messa#e 8ueues/
%hared Memory
File or ,ecord 9ocin#:
5sed to ensure that a process has e"clusi&e access to a
file before usin# it.
."amples:
-lpr #enerates a uni:ue se:uence number for each print ;ob.
Pid <3== se: <3>
.&ery process submitts a print ;ob to print
Process.
Pid < 3=3 se: <3>
Pid < 3=3 se: <4>
Pid < 3=3 se: <?>
Pid < 3=3 se: <@>
Pid < 3=3 se: <A>
Pid < 3== se: <4>
Pid < 3== se: <?>
Pid < 3== se: <@>
Process.
Print process has to assi#n a id to the ;ob.
PIB of re:uestin# process can not be used
%ince ;ob may re:uire more time to complete
!nd mean while the process mi#ht ha&e ended
up
!d&isory and Mandatory 9ocin#:
!d&isory locin# C
$% maintains the information of loced files but do not
pre&ents other process to write the file loced by
one process.
! process can i#nore the locin# and access the loced file
*his is suitable for co-operatin# processes.
%ystem - rel-II and @.?2%B pro&ides ad&isory locin#
Mandatory 9ocin# C
$% checs e&ery read and write for loced resources.
%ystem - rel-III pro&ides both type of locin#.
*o enable mandatory locin# on a file mae its
#roup-e"ecute bit C off
set-#roup-IB - on
File 9ocin# &erses ,ecord 9ocin#
For %ystem -:
Dinclude Eunistd.hF
int locf'int fd/ int function/ lon# si6e(>
fd---file descripter'not a file pointer(
si6e--- define the record si6e or loc area: Goffset/ offset H si6eI. si6e--- define the record si6e or loc area: Goffset/ offset H si6eI.
si6e<= means the rest of the file.
5se lsee'( to mo&e the current offset.
When the offset position is set to the be#innin# and si6e<= then
loc the whole file.
function:
FJ59$CK---unloc a pre&ious loc
FJ9$CK ---loc a re#ion'blocin#(
FJ*9$CK ---*est and loc a re#ion'nonblocin#(
FJ*.%* ---*est a re#ion to see if it is loced.
."ample: 5se FJ*9$CK instead of FJ*.%* and FJ9$CK.
If 'locf'fd/ FJ*.%*/ si6e(< <=(
+L If the re#ion is loced/ -3 is returned and the process is in sleep
stateL+
,e< locf'fd/ FJ9$CK/ si6e(>
+La small chance that another process locs between *.%* and
9$CKL+
M
rc<locf'fd/ FJ*9$CK/ si6e( rc<locf'fd/ FJ*9$CK/ si6e(
+L *est H loc done as an atomic operation/ If unsuccessful/ locf'(
returns C3 and the callin# process continues to do other thin#sL+
!tomic operation:
one or more operations that are treated as a sin#le operation. No
other operation can be e"ecuted between the start and end of an
atomic operation.
@.? 2%B !d&isory 9ocin# :
DincludeEsys+file.hF
int floc'int fd/ int operation(
$pearations:
9$CKJ%1 - %hared loc
9$CKJ.N - ."clusi&e loc
9$CKJ5N - 5nloc 9$CKJ5N - 5nloc
9$CKJN2 - Bo not bloc when locin#
9$CKJ%1 O 9$CKJN2 - %hared loc 'non blocin#(
9$CKJ.N O 9$CKJN2 - ."clusi&e loc 'non blocin#(
If call is successful returns = on fail -3
If loc fails because the file is already loced and a non blocin# loc
Was re:uested the #lobal errno is set to .W$59B29$CK
$ther 9ocin# *echni:ues 5NIN:
*hree features of 5NIN file system can be e"ploited to pro&ide a
type of locin#.
*his techni:ue depends on creation and use of a ancillary file to
Indicate that the resource has been loced by a process.
If the ancillary file is not present then the process demandin# the
,esource can create the ancillary file to indicate the resource has
2een loced by this process. 2een loced by this process.
Features used for locin#:
3. *he lin system call fails if the new lin to the file already
e"ists
4. Create system call fails if the file already e"ists and the caller
does not ha&e the write permission for the file.
?. Newer &ersion of 5NIN support options to the open system
call that causes it to fail if the file already e"ists.
9in system call:
int lin 'char Le"istin#path/ char Lnewpath(>
taes the e"istin# file and creates new directory lin to the
e"istin# path.
In 5ni" it possible to create any number of lins to a file
but with different names.
if the new lin already e"ists then the call fails and the #lobally
declared errno &arible is set to ..NI%* declared errno &arible is set to ..NI%*
'#lobal declaration e"tern int errno(
Create system call:
if create system call is e"istin# file/ the file #ets truncated to
= len#th/ if user has write permission on the file.
If the user is not ha&in# write permission then create fails
and errno is set to .!CC.%.
."ception: - If the user is superuser then he is ha&in# write
permission on all files and hence the concept fails.
Few Points to consider about these three techni:ue:
3. Create and lin wors under any &ersion of 5NIN.
4. *echni:ue taes more time than actual file locin# call.
?. !ncillary file is re:uired in addition to resource file.
@. !ncillary file may present on the system e&en after the
,esource is released if the system crashes before !ncillary
file is deleted. some techni:ue is necessary to handle this
%ituation.
A. 9in system call can not create a lin between file on different
File system. %o temporary file can not be placed on +tmp
File system File system
P. Create techni:ue does not wor for process with superuser
Pri&ile#es.
Q. $nce a process ac:uires a loc/ the other process can not
Betermine when to chec a#ain. *here is no mechanism
to notify the waitin# process when the loc is a&ailable.
R. *he process that has ac:uired the loc can be teminated
intentionally or unintentionally without releasin# the loc.
%imple Client-%er&er or IPC model:
PIP.
! pipe pro&ides a one-way flow of data.
%ystem call:
int pipe'int L filedes(>
filedesG=I is opened for readin#>
filedesG3I is opened for writin#
filedesG=I
filedesG3I
filedesG=I
filedesG3I
%ystem calls used to read and write pipe:
system calls used for readin# and writin# file are also
useful for pipes
read' readfd/ buf/ numbytes(
write' writefd/ buf/ numbytes(
%imple ."ample usin# Pipe:
main'(
S
int pipefdG4I>
int wrbytes/ readbytes>
char buffG3==I>
if 'pipe'pipefd( E = (
S
printf'Tpipe errorU(> printf'Tpipe errorU(>
e"it'=(>
V
wrbytes < write'pipefdG3I/ Thello worldWnU/ 34(>
if'wrbytes X< 34(
S
printf'Tpipe writin# errorU(>
V
readbytes < read'pipefdG=I/buff/si6eof'buff((>
printf'Tnumber of bytes read < YdU/readbytes(>
V
*his is not the appropriate use of Pipe
Pipe to communicate across two different processes
%teps:
3. ! process creates a pipe.
4. it fors to create a new process
?. if parent closes read then child closes write to ha&e
parent write the pipe and child read.
@. opposite case is also possible.
Pipes between two processes: bidirectional
%teps:
3( create pipe3 H pipe4
4( forin# off a child process/ e"ecutin# another pro#ram as a
ser&er
?( parent closes read end of pipe 3 H write end of pipe 4/
@( child closes write end of pipe 3 H read end of pipe 4 @( child closes write end of pipe 3 H read end of pipe 4
Properties of Pipe:
3( Pipes do not ha&e a name. For this reason/ the processes must
share a parent process. *his is the main drawbac to pipes.
1owe&er/ pipes are treated as file descriptors/ so the pipes remain
open e&en after for and e"ec.
4( Pipes do not distin#uish between messa#es> they ;ust read a
fi"ed number of bytes. Newline 'Wn( can be used to separate
messa#es. ! structure with a len#th field can be used for
messa#e containin# binary data. messa#e containin# binary data.
?( Pipes can also be used to #et the output of a command or to
pro&ide input to a command
Bisad&anta#e of Pipe:
Pipe can only be used to communicate between the
Processes that has a common parent process. 5nrelated processes
can not use pipe.
*he standard I+$ library pro&ides a function that creates a pipe
and initiates another process that either reads from the pipe or
writes to the pipe.
Dinclude Estdio.hF
FI9. Lpopen'const char Lcommand/ const char Ltype(>
Command C the shell command line that will be e"ecuted by
bourne %hell.
Pipe is created between the callin# process and the specified
Command
*ype C indicates readin# from or writin# to command
if type is TrU/the process reads the standard output of
the command.
if type is TwU/ the process writes to the command
e": cat command needs data from process.
*he call returns file pointer that is used to read+write data.
*o close the pipe use:
int pclose'FI9. Lstream(>
FIF$:
! FIF$ is similar to a pipe.
! FIF$ 'First In First $ut( is a one-way flow of data.
FIF$s ha&e a name/ so unrelated processes can share the FIF$.
FIF$ is a named pipe.
Creat: ! FIF$ is created by the mfifo function:
Dinclude Esys+types.hF
Dinclude Esys+stat.hF
int mfifo'const char Lpathname/ modeJt mode(>
pathname C a 5NIN pathname 'path and filename(. *he
name of the FIF$
mode C the file permission bits.
FIF$ can also be created by the mnod system call/
e.#./ mnod'Tfifo3U/ %JIFIF$O=PPP/ =( is same as
mfifo'Tfifo3U/ =PPP(.
$pen: mfifo tries to create a new FIF$. If the FIF$ already
e"ists/ then an ..NI%* error is returned. *o open an e"istin#
FIF$/ use open'(/ fopen'( or freopen'(
Close: to close an open FIF$/ use close'(. *o delete a created
FIF$/ use unlin'(.
command C mnode fifo3 p
Properties: ' %ome of them are also applicable to PIP.%(
3. !fter a FIF$ is created/ it can be opened for read or write.
4. Normally/ openin# a FIF$ for read or write/ it blocs until another
process opens it for write or read.
?. ! read #ets as much data as it re:uests or as much data as the
FIF$ has/ whiche&er is less.
@. ! write to a FIF$ is atomic/ as lon# as the write does not e"ceed the
capacity of the FIF$. *he capacity is at least @.
A. ,ead+Write operations are 2loced if read from an empty FIF$/ or
write to a full FIF$.
P. *he $JNB.9!Z fla# or $JN$N29$CK fla# can be set for FIF$ to P. *he $JNB.9!Z fla# or $JN$N29$CK fla# can be set for FIF$ to
affect the beha&ior of &arious operations. *his pre&ents accesses to
the FIF$ from blocin#.
."ample: how to set the fla#s?
writefd<open'FIF$3/ $JW,$N9Z O $JN$N29$CK/ =(
Q. For a pipe/ howe&er/ fcntl'( must be used to set this option. *his is
because pipes are opened as part of the pipe'( system call:
int fla#s>
fla#s<fcntl'fd/ FJ[.*F9/=(> +L #et the fla#s L+
fla# O< $JN$N29$CK>
fcntl'fd/ FJ%.*F9/ fla#s(> +L set the new fla#ts L+
Operation
Existing opens of
pipe or FIFO
Blocking (default)
O_NONBLOCK
set
Open FIFO
for reading
FIFO open for writing eturns OK eturns OK
FIFO not open for
writing (!)
Blocks until FIFO is
opened
for writing
eturns OK (")
Open FIFO for
writing
FIFO open for reading eturns OK eturns OK
FIFO not open for
reading(!)
Blocked until FIFO is
opened for reading
eturns an error
of
EN#IO($)
%ipe or FIFO open for
Blocked until t&ere is
data or t&e pipe or
eturns an error
of
ead e'pt(
pipe or FIFO
%ipe or FIFO open for
writing
data or t&e pipe or
FIFO is closed for
writing
of
E)*)IN($)
%ipe or FIFO not
open for writing (+)
ead returns , (EOF)
ead return ,
(EOF)
-rite to pipe or
FIFO
%ipe or FIFO open for
reading
eturn OK eturn OK
%ipe or FIFO is full
Blocked until space
is a.aila/le0 t&en
write data
eturns an error
of
E)*)IN ($)
%ipe or FIFO not open
for reading (+)
1I*%I%E generated0
write
process ter'inated
eturns an error
of
E%I%E ($)
3. FIF$ must be opened by two processes> one opens it as reader on
one end/ the other opens it as sender on the other end.*he
first+earlier opener has to wait until the second+later opener to
come. *his is somewhat lie a hand-shain#.
4. If one end of a PIP.+FIF$ is bein# read or written/ but the other
end is not open for writin# or readin#/ that is usually because the
other end was once opened but now is closed.
?. When a system call returns C3 on error/ a specific reason or error
number is stored in errno/ such as ..NI*/ .NNI$/ .![!IN. *he number is stored in errno/ such as ..NI*/ .NNI$/ .![!IN. *he
&alue of such symbolic constants are defined in Esys+errno.hF.
Whene&er an error occurs/ you can use perror' ( to print a system
error messa#e describin# the last error encountered durin# a
system call or library function.
@. $nly in this case/ $JN$N29$CK maes the ori#inally bloced
operation return immediately without error.
Name %pace:
*he set of possible names for a #i&en type of IPC.
e": ey
! ey is a lon# int/ used to identify indi&idual resources.
Name allows different processes to reco#ni6e the IPC
channel they are usin# to communicate each other.
IPC Keys
)Keys are numbers used to identify an IPC ob;ect on a 5NIN system
)Much lie a file name bein# used to identify files
)Key allows IPC ob;ects to be shared by se&eral processes
Difference between keys and file names Difference between keys and file names Difference between keys and file names Difference between keys and file names
Keys are not file names and carry less meanin#
!ctual ey type is determined by implementation/ and
defined by eyJt in Esys+types.hF
5NIN uses a simple library function that maps a file0s
pathname to a ey
) ,outine is called fto' (
) *hus it is possible to start with a pathname and #et a
ey #enerated automatically from the pathname
KeyJt fto'char Lpathname/ char pro;(
If path name does not e"ists/ fto returns -3
Client and ser&er a#rees upon certain pathname and pro;
Fto combines R bit pro;/ inode number of file and minor de&ice
Number of file system to produce ?4 bit eyJt.
Fto is not a fullproof since there is a chance that different
Pathname may produce same ey. Pathname may produce same ey.
fto'( pathname
pro;
KeyJt ms##et
sem#et
shm#et
int id
%ystem - IPC
*hree types of IPC:
) messa#e :ueues
) semaphore
) shared memory
%ummary of %ystem - IPC system calls:
ipcs 7 7 7 7 lists current IPC resources
5ni" commands to determine IPC resources
ipcrm 7 7 7 7 delete an IPC resources
ipcJperm structure:
%imilar to file ernel maintains a structure of Information for
each IPC channel:
struct ipcJperm S
ushort uid> ++ owner0s user id
ushort #id> ++ owner0s #roup id
ushort cuid> ++ creator0s user id
ushort c#id> ++ creator0s #roup id ushort c#id> ++ creator0s #roup id
ushort mode> ++ access mode
ushort se:> ++ slot usa#e se:uence number ++ details further
eyJt ey> ++ ey
V>
Befined in Esys+ipc.hF
When an IPC channel is created/ the owner and creator0s user id is
%et to effecti&e user id of process and similarly for #roup id.
$wner user id can be chan#ed but not creator0s user id.
Creatin# or openin# the IPC channel:
Ms##et/ sem#et/ or shm#et taes two ar#uments:
ey C identifies the channel.
fla# C permission mode lower \ bit.
fla#s for cratin# ipc channel with additional parameters.
IPCJC,.!*./ IPCJ.NC9
*he rules for whether a new IPC channel is created or whether an
."istin# to be used are: ."istin# to be used are:
3. %pecifyin# ey of IPCJP,I-!*. #uarantees that a uni:ue IPC
channel is created. Fto can not be used for #eneratin# ey
&alue of IPCJP,I-!*..
4. %ettin# IPCJC,.!*. fla# in fla# ar#ument C creates a new IPC
channel if not e"istin# and if IPC channel with specified entry
already e"ists/ then same is returned.
?. %ettin# both IPCJC,.!*. and IPCJ.NC9 of fla# creates a new IPC
channel for specified ey it already do not e"ists. If IPC channel
already e"ists the it returns error.
IPCJ.NC9 does not indicate e"clusi&e access to channel. It only
indicate that the new ipc channel is crated if channel already
does not e"ists or else it returns error.
other users can access the IPC channel created with IPCJ.NC9 if
they posses sufficient permission.
IPCJ.NC9 has no meanin# without IPCJC,.!*..
Permission Checin# durin# an IPC !ccess by a process:
3. IPC channel is already created and another process tries to create
the channel with same ey but with different permissions.
- results into error returned bac.
4. IPC channel is already created and another process wants to
access the channel by specifyin# = as fla# parameter.
- permission is checed on the basis of user tryin# to
access the channel.
for e"ample if channel is created with read+write for e"ample if channel is created with read+write
permission for owner and if non owner user attempts to
access the channel then he will be returned error.
followin# can be common rules in this respect:
a. %uperuser has always access.
b. If effecti&e userid e:uals uid or cuid of :ueue then
IPC channel is accordin# to mode bits for owner.
c. same as in b for effecti&e #roup id of process accessin#
IPC channel.
d. if b and c is not true then permission for others are
tested.
%lot usa#e se:uence number:
*his a counter maintained by ernel for e&ery ipc channel in
the system.
Whene&er a ipc channel is closed the slot number is incremented
by one. Cyclin# bac to 6ero when o&erflows.
*his number is returned to the callin# process when it tries to
!ccess the channel by callin# any one of L#et sys call.
Need of slot usa#e se:uence number:
3. #et system calls used for ipc channel returns a inte#er id
similar to file system call. 2ut file are open locally for a process
and IPC channel is central resources shared by many
processes usin# a common identifier.
4. 5nder this situation a process may try to access the channel
without e"clusi&ely openin# it by attemptin# different ids/ if the
ids are small numbers lie file descriptors.
?. Kernel chan#es these ids e&ery time the IPC channel is used
so that no #uess is possible.
@. If currently the id returned is = then if channel is remo&ed
and created once a#ain the id returned is A='if ma" no. of channel
allowed of this ind is A=(
Messa#e 8ueues
Messa#e 8ueues7Why necessary?
Brawbac of PIP. and FIF$:
3( Pipe or FIF$ is an unformatted stream. Messa#e :ueue is a formatted
stream consisted of messa#es.
4( Pipe or FIF$ has to be read in the same order as they are written. 4( Pipe or FIF$ has to be read in the same order as they are written.
Messa#e :ueue can be accessed randomly.
?( Pipe or FIF$ is unidirectional. Messa#e :ueue is bidirectional.
@( Pipe or FIF$ is simple". Messa#e :ueue is multiple".
A( Messa#e :ueue is faster since it is in ernel
! messa#e :ueue is created or opened usin#:
int ms##et'eyJt ey/ int ms#fla#(
ms#fla# 7 sets permission H IPCJC,.!* + IPCJ.NC9.
ms#id 7 returned by the ms##et'( function/ -3 on error.
1ending 2essages 3
int ms#snd'int ms#id/ struct ms#buf Lptr/ int len#th/ int fla#(
len#th 7 determine how many bytes of data portion are sent.
fla# 7 can be IPCJN$W!I* which causes the function to return
immediately with error<.![!IN if no :ueue space is a&ailable.
Befault action is to bloc. Befault action is to bloc.
return 7 = if successful> -3 on error.
struct ms#buf -- messa#e format/ has a lon# int 'messa#e type( as a
field/ immediately followed by the data. Must be
filled by caller before callin# ms#snd' (.
struct ms#buf S
lon# type>
char dataGI>
V
!bout Messa#e 2uffer %tructure:
*he structure of messa#e buffer shown earlier is ;ust a template.
*he messa#e sender can declare other structure whose format
Is same as template modifyin# the name of structure as well
!s member &ariables in the structure.
Mandatory part of this structure is the first field C lon# Ms#type
- this identifies the messa#e within :ueue - this identifies the messa#e within :ueue
- name of this can be chan#ed.
%econd part of messa#e structure is the data array.
- this does not mean only te"t data can be placed inside
messa#e.
- data array can hold any type of data 'e&en binary(
- suitable structure can be used to store actual data.
Messa#e %tructure ."ample:
struct myms#
S
lon# mtype>
char Ldata>
V
struct myms# m3>
struct myrec Lmr < 'struct myrecL(malloc'si6eof'struct myrec((>
m3.mtype <3==>
struct myrec
S
int roll>
char nameG3==I>
float total>
V
m3.mtype <3==>
m3.data < 'charL(mr>
Ms#snd'ms:id/]m3/si6eof'struct myrec(/=(>
Messa#es are recei&ed usin#:
int ms#re&'int ms#id/ struct ms#buf Lptr/ int len#th/ lon# ms#type/
int fla#(
len#th 7 specify the si6e of the data buffer. .rror if the messa#e is
too lon#.
$K if the len#th ^ messa#e len#th which is determined by
ms#snd'Mlen#thM(.
fla# 7 if set to M%[JN$.,,$,/ lon# messa#es are truncated and the
rest is discarded. If set to IPCJN$W!I*/ function return C3 if no
matchin# messa#es are found/ otherwise bloc until
! messa#e with the appropriate type is placed on the :ueue.
*he messa#e :ueue is remo&ed from the system.
*he process recei&es a si#nal that is not i#nored.
Ms#type:
< =: read the first ms# on the :ueue.
F=: read the first ms# on the :ueue with this type.
E=: read the first ms# on the :ueue with the
lowest type _ O ms#typeO
return 7the len#th of the data recei&ed in bytes if successful> -3
on error.
Controllin# Messa#e 8ueue operation:
int ms#ctl'int ms#id/ int cmd/ struct ms#-id-ds Lbuff(
*o remo&e a ms# :ueue/ cmd < IPCJ,MIB> the ?
rd
parameter is ;ust
a N599 pointer.
*o #et+set the :ueue information in buff/ cmd < IPC-%*!*+IPC-%.*.
Multiple"in# Messa#es:
%emaphore
%emaphores are not used to e"chan#e a lar#e amount of data.
%emaphores are used for synchroni6ation amon# processes.
$ther synchroni6ation mechanisms include record locin# and
mute"es. mute"es.
Why necessary? ."amples
include: shared washroom/ common rail se#ment/ and common
ban account.
! semaphore set is created usin#:
int sem#et'eyJt ey/ int nsems/ int semfla#(>
nsems 7 D of semaphores/ use multiple semaphores for
multiple resources. multiple resources.
semfla# 7%ame as ms#fla#/ sets permission and creation
options.
returns int semid> the id of the semaphore set> -3 on error.
Key Points about %emaphores:
3( ! process ac:uires the semaphore if it has a &alue of 6ero. *he
&alue of the semaphore is then incremented to 3. When a process
releases the semaphore/ the &alue of the semaphore is
decremented.
4( If the semaphore has non-6ero &alue when a process tries to
ac:uire it/ that process blocs.
?( When a process waits for a semaphore/ the ernel puts the ?( When a process waits for a semaphore/ the ernel puts the
process Tto sleepU until the semaphore is a&ailable. *his is better
'more efficient( than busy waitin# such as *.%*]%.*.
@( *he ernel maintains information on each semaphore
internally/ usin# a data structure Tstruct semisJdsU that eeps
trac of permission/ number of semaphores/ etc.
A( !pparently/ a semaphore in 5ni" is not a sin#le binary &alue/
but a set of nonne#ati&e inte#er &alues
Kernel Bata %tructure for %emaphore:
Control operations are performed usin#:
int semctl'int semid/ int semnum/ int cmd/ union semum ar# (>
` ,eturn &alue depends on cmd/ -3 on error.
cmd --- IPCJ,MIB to remo&e a semaphore set. 5nion semun ar# is not
used in this case.
[.*-!9 +%.*-!9 to fetch+set a specific &alue. semnum can
specify a member of the semaphore set.
when [.*-!9 is used/ the &alue of semaphore is returned
as functions return &alue.
[.*!99+%.*!99 to fetch+set all &alues of the semaphore set.
union semun
S int &al> +L used for %.*-!9 only L+
stuct semidJds Lbuff +L used for IPCJ%*!* and IPCJ%.* L+
ushort Larray +L used for [.*!99 and %.*!99L+
V ar#>
$perations on a semaphore are performed usin#:
int semop'int semid/ struct sembuf Lopsptr/ unsi#ned int nops(
semid7 &alue returned by sem#et.
nops7 D of operations to perform/ or the number of elements in the
opsptr array.
$psptr 7 points to an array of one or more operations. .ach
operation is defined as:
struct sembuf S
ushort semJnum> +L semaphore D/ numbered from =/ 3/ 4 M L+
short semJop> +L semaphore operation L+ short semJop> +L semaphore operation L+
short semJfl#> +Loperations fla#s/ such as =/ IPCJN$W!I* for
nonblocin# call/ or %.MJ5NB$ to ha&e the semaphore automatically
released when the process is terminated prematurely.L+
V>
semJop < = C wait until the semaphore is =. IPCJN$W!I* causes
an error if sem&ala=.
semJop F = C increment the semaphore &alue: sem&al H semJop/
'ac:uire(
semJop E = C wait until the semaphore &alue^OsemJopO and
decrement the semaphore &alue: sem&al - OsemJopO/ 'release(
%hared Memory %hared Memory
5sin# a pipe or a messa#e :ueue re:uires multiple e"chan#es of
data throu#h the ernel. %hared memory can be used to bypass
the ernel for faster processin#.
*he ernel maintains information about each shared memory se#ment/
includin# permission/ si6e/ access time/ etc in struct shmidJds .
struct shmidJds loos lie struct semidJds or as struct ms:idJds .
! share memory se#ment is created usin#:
int shm#et'eyJt ey/ int si6e/ int shmfla#(>
si6e --- si6e of the shared memory se#ment in bytes. si6e --- si6e of the shared memory se#ment in bytes.
shmfla# --- same as for ms##et'( and sem#et'(/
,eturn &alue --- shmid/ the shared memory identifier/ -3 on
error.
!ttach to the shared memory se#ment usin#:
char Lshmat'int shmid/ char Lshmaddr/ int shmfla#(
shmid --- return &alue of shm#et/ that is/ the id of the created
shared memory.
shmaddr--- =: let the ernel select the address.
shmfla#--- %1MJ,B$N9Z for readJonly access.
returns the startin# address of the shared memory/ and thus
we can read+write on the shared memory after #ettin#
its startin# address.
Betach the shared memory se#ment usin#:
char Lshmdt'char Lshmaddr(
shmaddr --- the return &alue of shmat'(/ that is/ the startin# address
of the shared memory.
returns C3 on failure.
*o remo&e a shared memory se#ment:
Int shmctl'int shmid/ int cmd/ shmidJds Lbuf(>
cmd--- IPCJ,MIB to delete/ e.#./ shmctl'shmid/ IPCJ,MIB/ =( .
.nd .nd

Das könnte Ihnen auch gefallen