of 26
8/12/2019 Unix.interprocess.communication
1/26
8/12/2019 Unix.interprocess.communication
2/26
Create i! it does not already
existexclusive create
O*C,7%
O*7XC/
O*C,7%
O*7XC/
O*C,7%
O*7XC/
&on#locking moderuncate i! it already exists
O*&O&8/OC9O*,:&C
% message queue can #e opened in any o! the three modes' read-only" write-only andread-write$
,ead and write access #oth are required !or any semaphore operation so it is de!ault !or
semaphore$% shared memory o#)ect cannot #e write only$
,emaining !lags are optionalO*C,7% ; Creates the message queue" semaphore" or shared memory o#)ect i! it
doesnot already exist$
O*7XC/ ; i! this !lag and O*C,7% are #oth speci!ied" then the !unction creates a new
message queue" semaphore" or shared memory o#)ect only i! it doesnot already exist$ I! italready exist" an error o! 77XIS is returned$
&ote' he check !or the existence o! an IPC and its creation must #e an atomic operation$
O*&O&8/OC9- his !lag makes a message queue non#locking with regard to a read onan empty queue or a write to a !ull queue$
O*,:C- i! an existing shared memory o#)ect is opened read-write" this !lag speci!ies
that the o#)ect #e truncated to < length$
=
8/12/2019 Unix.interprocess.communication
3/26
8/12/2019 Unix.interprocess.communication
4/26
I! the e!!ective user I+ o! the process equals the owner id o! the IPC o#)ect' i! the
appropriate user access permission #it it set" access is allowed" else access isdenied$
I! the e!!ective group I+ o! the process or one o! the supplemenatary group I+s o!
the process equals the group I+ o! the IPC o#)ect' i! the appropriate group accesspermission #it is set" access is allowed" else permission is denied$
I! the appropriate other access permission #it is set" access is allowed" else
permission is denied$hese !our steps are tried in sequence in the order listed$ here!ore" i! the process
own the IPC o#)ect" then access is granted or denied #ased only on the user access
permissions ; the group permissions are never considered$ Similarly" i! the processdoes not own the IPC o#)ect" #ut the process #elongs to an appropriate group" then
access is granted or denied #ased only on the group access permissions ; the other
permissions are not considered$
POSIX Message queue
% message queue can#e thought o! as a linked list o! messages$ hread with adequatepermission can put messages onto the queue" and threads with adequate permission
can remove message !rom the queue$ 7ach message is assigned some priority$
&o requirement exist that someone #e waiting !or a message to arrive on a queue#e!ore some process writes a message to that queue$ his is in contrast to Pipes and
FIFOs$
% process can write some messages to a queue" terminate and have the messages read#y another process at a later time$
Message queues have kernel persistence in contrast to pipes and !i!o" which are only
process persistent$ %ny data remaining in a pipe or FIFO when the last close o! thepipe or FIFO takes place" is discarded$
POSIX M2 vs System A M2
% read on a Posix message queue always returns the oldest message o! the highestpriority" where as a read on a system A message queue can return a message o! any
desired priority$
Posix message queue allow the generation o! a signal or the noti!ication o! a threadwhen a message is placed onto an empty queue" whereas nothing similar is provided
#y system A message queue$
7very message on a message queue has !ollowing attri#utes % unsigned integer priority
he length o! the data portion o! the message
he data itsel!
he POSIX message queue !unctions are'
B
8/12/2019 Unix.interprocess.communication
5/26
mq_open(); Creates a new message queue or opens an existing message queue$
include4mqueue$h5
mqd*t mq*openDconst char Ename" int o!lag" $ $ $
6E mode*t mode" struct mq*attr Eattr E6 G
name ; Posix IPC name usually unix path name$
o!lag ; one or more !lag constants descri#ed #e!ore$
mode H attr ; required when new queue is created$
mq_close()-- 7nds the connection to an open message queue$
mq_unlink()-- 7nds the connection to an open message queue and causes the queue
to #e removed when the last process closes it$
Message queue have a re!erence count o! how many times they are currently open$mq*unlink call decrements re! count #y 1 and causes a queue to #e removed !rom the
system when this re! count #ecomes ero$
mq_send()-- Places a message in the queue$
mq_receive() -- ,eceives Dremoves the oldest" highest priority message !rom thequeue$
mq_notify()-- &oti!ies a process or thread that a message is availa#le in the queue$
mq_setattr()-- Set or get message queue attri#utes$
IPC' Semaphore
Semaphores are a programming construct designed #y 7$ .$ +i)kstra in the late 1JK
8/12/2019 Unix.interprocess.communication
6/26
Posix semaphores need not to #e maintained in the kernel$ %lso" Posix semaphores are
identi!ied #y names that might correspond to pathnames in the !ile system$
hree #asic operations that a process can per!orm on a semaphore
Create a semaphore - his also requires a caller to speci!y the initial value which !or
a #inary semaphore is o!ten 1 #ut can #e
8/12/2019 Unix.interprocess.communication
7/26
sem_unlink() -- 7nds the connection to an open semaphore and causes the
semaphore to #e removed when the last process closes it$
sem_destroy() -- Initialies a semaphore structure Dinternal to the calling program"
so not a named semaphore$
sem_wait(), sem_trywait() -- 8locks while the semaphore is held #y other
processes or returns an error i! the semaphore is held #y another process$
sem_post()-- Increments the count o! the semaphore$
IPC' Message 2ueue
he #asic idea o! a message queueis a simple one$two Dor more processes can exchange in!ormation via access to a common system
message queue$ he sendingprocess places via some DOS message-passing module a
message onto a queue which can #e read #y another process DFigure =B$1$ 7ach message
is given an identi!ication or typeso that processes can select the appropriate message$
POSIX messages
he POSIX message queue !unctions are'
mq_open()-- Connects to" and optionally creates" a named message queue$
mq_close()-- 7nds the connection to an open message queue$
mq_unlink()-- 7nds the connection to an open message queue and causes the queue
to #e removed when the last process closes it$
mq_send()-- Places a message in the queue$
mq_receive() -- ,eceives Dremoves the oldest" highest priority message !rom the
queue$
mq_notify()-- &oti!ies a process or thread that a message is availa#le in the queue$
mq_setattr()-- Set or get message queue attri#utes$
http://c/Documents%20and%20Settings/Administrator.INAPP-P518CUIJY/Desktop/np/beej%20ipc/C/node25.html#fig:messagehttp://c/Documents%20and%20Settings/Administrator.INAPP-P518CUIJY/Desktop/np/beej%20ipc/C/node25.html#fig:message8/12/2019 Unix.interprocess.communication
8/26
Shared Memory IPC
Shared is !astest !orm o! IPC availa#le$ Once the memory is mapped into the address
space o! the processes that are sharing the memory region" no kernel involvement occursin passing data #etween the processes$
Synchroniation is required #etween processes #etween processes that are storing and
!etching in!ormation to and !rom the shared memory region$
we discussed various !orm o! synchroniation ' mutexes" condition varia#les" locks and
semaphores$
Common steps in using shared memory
he server gets access to a shared memory o#)ect using a semaphore$
he server reads !rom the input !ile into the shared memory o#)ect$ he second
argument to the read" the address space o! the data #u!!er" points to the sharedmemory o#)ect$
.hen the read is complete" the server noti!ies the client" using a semaphore$ he client writes the data !rom shared memory o#)ect to the o6p !ile$
Common !unction !or shared memory IPC
shm*open ; speci!ies a name argument Dunix pathname " to either create a new sharedmemory o#)ect or to open an existing shared memory o#)ect$
mmap ; maps either a !ile or a Posix shared memory o#)ect into the address space o! a
process$ It is de!ined in 4sys6mman$h5
munmap ; removes a mapping !rom the address space o! the process$
msync ; the kernel(s virtual memory algorithm keeps the memory mapped !ile Don disk
synchronied with the memory mapped region in memory$ his !unction makes certain
that #oth copies synchronied$
shm*unlink ; removes the name o! a shared memory o#)ect$
!truncate ; to speci!y the sie o! a newly created shared memory o#)ect or to change the
sie o! an existing o#)ect$
!stat - when we open an existing shared memory o#)ect"we call !stat to o#tain
in!ormation a#out the o#)ect$
System V IPC
Q
8/12/2019 Unix.interprocess.communication
9/26
hree types o! IPC
System A message queue
System A semaphores
System A shared memory
are collectively known as RSystem A IPC$ hey share many similarities in the !unctions
that access them" and in the in!ormation that the kernel maintains on them$Message
2ueue
Semaphores Shared
memory
3eader 4sys6msg$h5 4sys6sem$h5 4sys6shm$h5
Function to create oropen
msgget semget shmget
Functions !or
control operation
msgctl semctl shmctl
Functions !or IPC
operations
msgsnd
msgrcv
semop shmat
shmdt
System V IPC Name:
he there types o! IPC are noted as using key*t values !or their names$ he header
4sys6types$h5 de!ines the key*t datatype" as an integer" normally at least a @=-#it integer$hese integer values are normally assigned #y the !tok !unction$
he !unction !tok converts an existing pathname and an integer identi!ier into a
key*t value$
include4sys6ipc$h5key*t !tok Dconst char Epathname" int idG
returns' IPC key i! O9" -1 on error
his !unction takes in!ormation derived !rom the pathname and the low order Q #its o! idand com#ines them into an integer IPC key$
3ere" the id argument is used to create multiple IPC channels o! same path name$ Forexample" i! client and server need two IPC channels say one !rom client to server and one
!rom server to client" then one channel can use an id o! one and another can use id o! two$
ypical implementations o! !tok call the stat !unction and then com#ines
In!ormation a#out the !ile system on whichpathname resides
he !ile(i-node num#er within the !ile system
he low order Q #its o! the id.he com#ination o! these three values normally produces a @=-#it key$
ipc_perm structurehe kernel maintains a structure o! in!ormation !or each IPC o#)ect" similar to thein!ormation it maintains !or !iles
include4sys6ipc$h5
struct ipc*permT uid*t uidG 6E owner(s user id E6
gid*t gidG 6E owner(s group id E6
uid*t cuidG 6E creator(s user id E6
J
8/12/2019 Unix.interprocess.communication
10/26
gid*t cgidG 6E creator(s group id E6
mode*t modeG 6E read-write perm E6
ulong*t seqG 6E slot usage seq num#er E6 key*t keyG 6E IPC key E6
UG
Creating and Opening IPC channels
he three getXXX !unctions Dmsgget" semget and shmget etc$ that create or open an IPC
o#)ect all takes an IPC keyvalue whose type is key*t and return an integer identifier$I! IPC key isn(t already availa#le" pass IPC*P,IA%7 as key to getXXX !unction" a
unique IPC o#)ect is created$
Speci!ying a key o! IPC*P,IA%7 guarantees that a unique IPC o#)ect is created$ &o
com#inations o! pathname and id exist that cause !tok to generate a key value o!IPC*P,IA%7$
%ll three getXXX !unctions also take an oflagargument that speci!ies the read-write
permission #its !or the IPC o#)ect and whether a new IPC o#)ect is #eing created or anexisting one is #eing re!erenced$
.e o#tain an IPC identi!ier !rom one o! the get !unction' msgget" semget" shmget$ heseidenti!ier are integers" #ut their meaning applies to all processes unlike !ile descriptors$ I!
two unrelated processes" a client and a server" use a single message queue identi!ier
returned #y megget !unction must #e the same integer in order to access the samemessage queue$
his !eature means that a rogue process could try a read a message !rom some other(s
application(s message queue #y trying di!!erent small integer identi!ier" hoping !ind one
that is currently in use that allows world read access$ I! the potential values o! these weresmall integers then the pro#a#ility o! !inding a valid identi!ier would #e a#out 1 in
8/12/2019 Unix.interprocess.communication
11/26
he type !ield can #e used to identi!y the message" allowing multiple processes to
multiplex messages onto a single queue$ One value o! the type !ield is used !or messages
!rom the clients to the server" and a di!!erent value that is unique !or each client is used!orm messages !rom the server to the clients$ &aturally" the process I+ o! the client can
#e used as the type !ield that is unique !or each client$
he type !ield can #e used as a priority !ield$ his lets the receiver read the messages inan order other than FIFO$
System A shared memorySimilar in concept to Posix shared memory instead o! calling shm*open !ollowed #y
mmap" we call shget !ollowed #y shmat$
Common !unctions
shmget !unction- a shared memory segment is created or an existing one is accessed" #ythe shmget !unction$ he return value is an integer called theshared memory identifier.
hat is used with the three other shmXXX !unctions to re!er to this segment$
include4sys6shm$h5
int shm*getDkey*t key,sie*tsize, int oflagsG
key can #e either a value returned #y !tok or the constant IPC*P,IA%7$sie ; speci!ies the sie o! the segment" in #ytes$
o!lag ; com#ination o! read-write permissions$
shmat !unction ;
%!ter a shared memory segment has #een created or opened #y shmget" we attach it to
our address space #y calling shmat$
shmdt !unction ;when a process is !inished with a shared memory segment" it detaches the segment #y
calling shmdt$
shmctl ; provides a variety o! control operation on a shared memory segment$ likeremoving shared memory segment" setting permission #its and mode$
System A semaphore
he !unction semget()initialies or gains access to a semaphore$ It is prototyped #y'
int semget(key_t key, int nsems, int semflg);
.hen the call succeeds" it returns the semaphore I+ Dsemid$
he keyargument is a access value associated with the semaphore I+
semctl()changes permissions and other characteristics o! a semaphore set$
semop - operations are per!ormed on one or more o! the semaphore in the set using this
!unction$
1
8/12/2019 Unix.interprocess.communication
12/26
Doors
+oor calls are synchronous$ .ithin a process" doors are identi!ied #y descriptors$
7xternally" doors may #e identi!ied #y pathnames in the !ile system$
% server creates a door #y calling door*create" whose argument is a pointer to theprocedure that will #e associated with this door" and whose return value is a descriptor !or
the newly created door$
he server then associates a pathname with the door descriptor #y calling !attach$% client opens a door #y calling open" whose argument is the pathname that the server
associated with the door" and whose return value is the client(s descriptor !or this door$
he client then calls server procedure #y calling door*call$
% server !or one door could #e a client !or another door$+oor calls are synchronous' when the client calls door*call" this !unction does not return
until the server procedure returns$
.hen a server procedure is called" #oth data and descriptorscan #e passed !orm the
client to the server$ 8oth data and descriptor can also #e passed #ack !rom the server tothe client$ +escriptor passing is inherent to doors$
Since doors are identi!ied #y descriptors" this allows a process to pass a door to otherprocess$
Basic API functions:
door*call !unction ; is called #y a client and it calls a server procedure that is executingin the address space o! the server process$
include 4door$h5
int door*callDintfd,door*arg*t *argG
returns' < i! ok " -1 on errorhe descriptor !d is normally returned #y open$
he pathname opened #y the client !or identi!ierfd, identi!ies the server procedure to #e
called #y door*call$he =ndargument argp points to a structure descri#ing the arguments and the #u!!er to #e
used to hold the return values$
door*create !unction ; % server process esta#lishes a server procedure #y calling
door*create$
First arg to door*create !unction is the address o! the server procedure that will #e
associated with the door descriptor$
door*return ; when a server procedure is done it returns #y calling door*return$ his
causes the associated door*call in the client to return$
1
8/12/2019 Unix.interprocess.communication
13/26
Remote Procedure call
RPC provides an alternative way to write distributed application.
It allows different pieces of an application to execute on different host and providescommunication between them by calling procedure of one another.
So in RPC, we code our application using the familiar procedure call( lie local procedurecall !, but the calling process(the client! and the process containing the procedurebeing called(server! can be executing on different host.
Steps in writing RPC application
"rite RPC specification file has .x extension, define server procedure along with theirarguments and results.
struct s#uare$in% &' input(argument! '&
long arg)
*)
struct s#uare$out%&' output(argument! '&
long res)*)
program S+-R$PR/0%
version S+-R$1RS%
s#uare$out S+-RPR/C(s#uare$in! 2 )&'procedure number2'&
*2) &' version number '&
*23x4543333)
Step 2: Compiling RPC specification file(s#uare.x file! using rpcgen program. It
generates following files - header file that you will include in your programs6 s#uare.h
- server program which will call actual server procedure when re#uest isreceived!6 s#uare$svc.c also called server seleton
- client stub (that client program can use to send an RPC!
s#uare$clnt.c
Internal function to convert the procedure parameters into networmessages and vice7versa6 s#uare$xdr.c. xdr(external datarepresentation! must be shared by both server and client.
Step 3: Write client program.
Include header generated by rpcgen.8eclaring and obtaining client handler using clnt$create function.
9include:rpc&rpc.h;
C 'clnt$create(const char *host,unsigned longprognum, unsigned long versnum,const char *protocol!)
Returns6 nonnull client handle if /?, =
8/12/2019 Unix.interprocess.communication
14/26
prognum6 program name.
versnum6 version number.
protocol6 either >CP or 8P.
>ypical code on client side main function6C 'cl)&& declaring client handle.
s#uare$in in)
s#uare$out 'outp)
cl2clnt$create(@A5.B..D,3x4543333,,D>CPD!)&&obtaining client handle
outp2s#uareproc$(Ein,cl!)&& calling server procedure
Step 4: Call remote procedure and print result.
"e call procedure and first argument is a pointer to the input structure struct$in and thesecond argument is the client handle.
>he return value is a pointer to the result structure struct$out.
In our specification file, we named our procedure S+-RPR/C, but from the client wecall s#uareproc$. >he convension is that the name in the .x file is converted tolowercase and an underscore is appended, followed by the version number.
Step 5: writing server procedure
on the server side, all we write is our server procedure. rpcgen automaticallygenerates the server main function.
name of the server must be $svc appended following the version number. >his allowstwo -=SI C function prototypes in the generated .h header file, one for thefunction called by the client and one for the actual server function.
Server procedure has two argument6First is pointer to struct$in structure and
Second argument is a structure passed by the RPC runtime that contains information aboutthis invocation.
>ypical code for server procedure
s#uare$out s#uareproc$$svc(s#uare$in 'inp, struct svc$re# 'r#stp!
% static s#uare$out out)
out.res2 inp7;arg ' inp7;arg)
return(Eout!)
*
RPC files
>o write a minimalist RPC program, we must write
. - C procedure to be remotely called6 remoteproc.c
5. - specification of the procedure6 remoteproc.x
1
8/12/2019 Unix.interprocess.communication
15/26
4. - client program to re#uest the procedure6 client.c
Gased on specification file(remoteproc.x!, rpcgen program generates6
! - header file that you will include in your programs6 remoteproc.h
5! - server program which will call actual server procedure when re#uest is
received!6 remoteproc$svc.c also called server seleton4! - client stub (that client program can use to send an RPC!
remoteproc$clnt.c
H! Internal function to convert the procedure parameters into networmessages and vice7versa6 remoteproc$xdr.c
xdr(external data representation! must be shared by both server andclient.
Client needs with following files to compile6
. client.c client code, containing calling statement.
5. procedure$clnt.c client stub(generated!4. procedure$xdr.c handles parameter and return value marshalling or
conversion
H. procedure.h containing prototype of procedure that is called by client.
Server needs with following files to compile6
! serverprocedure.c contain actual remote procedure code.
5! procedur$xdr.c shared by both client and server
4! procedure$svc.c server stub
1
8/12/2019 Unix.interprocess.communication
16/26
XI ;x6open transport inter!aceXI uses the term communication provider to descri#e the protocol implementation$ he
commonly availa#le communication provider are the internet protocols" that is" CP or
:+P$he term communication end point re!ers to an o#)ect that is created and maintained #y a
communication provider and then used #y an application$
hese end point are re!erred to #y !ile descriptor$%ll Xti !unction #egins with t*$ he header that the application includes to o#tain all the
Xti de!inition is 4xti$h5$ some internet-speci!ic de!initions are o#tained #y including
4xti*inet$h5$
t_open function
include4xti$h5
include4!cntl$h5int t*openDconst char Epathname" int oflag" struct t*in!o EinfoG
esta#lishes a communication end-point is to open the :&IX device that identi!ies theparticular communication provider$
his !unction returns a descriptor that is used #y other XI !unctions$
he actual pathname to use depends on the implementation typical values !or CP6IP
endpoints are 6dev6tcp" 6dev6udp or 6dev6icmp$
1
8/12/2019 Unix.interprocess.communication
17/26
Oflag argument speci!ies the open !lags$ Its value is O*,+.,$ For a non-#locking end
point the !lag O*&O&8/OC9 is logically O,(ed with O*,+.,$he tin!o structure is a collection o! integer values that descri#e the protocol dependent
!eatures o! the provider$
struct t*in!oT
t*scalar*t addrG
t*scalar*t optionsG t*scalar*t tsduG
t*scalar*t etsduG
t*scalar*t connectG
t*scalar*t disconG t*scalar*t servtypeG
t*scalar*t !lagsG
UG
addr ; his speci!ies the max sie in #ytes o! a protocol speci!ic address$ % value o! -1
indicates that there is no limit to the sie$ For CP or :+P is sie o! sockaddr*in
structure$Options ; Sie in #ytes o! protocol speci!ic !unctions$
tsdu ; stands !or Rtransport service data unit$ his varia#le speci!ies the max sie in
#ytes o! record whose #oundaries are preserved !rom one endpoint to other$ % value o!