Anda di halaman 1dari 26

POSIX IPC

Following three IPC mechanism are collectively known as posix ipc


o POSIX Message queue
o POSIX Semaphores
o POSIX Shared memory
hey share some similarity in the !unctions that access them" and in the in!ormation that
descri#es them$
Following are the common properties
he pathnames used !or identi!ication
he !lags speci!ied when opening or creating
%ccess permissions
POSIX IPC !unctions
IPC &ames' he !irst argument to open !unctions a#ove three PIC technique must #e an
identi!ication name" which may or mayn(t #e real path name in a !ile system$
Creating and Opening IPC channels
he three !unctions that create or open an IPC o#)ect" mq*open" sem*open and
shm*open" all take a second argument named oflag that speci!ies how to open the
requested o#)ect$
he various constants that can #e used to !orm this argument are'
+escription mq*open sem*open shm*open
,ead-only
.rite-only
,ead- write
O*,+O&/0
O*.,O&/0
O*,+.,
O*,+O&/0
O*,+.,
1
Message
2ueue
Semaphores Shared
Memory
3eader 4mqueue$h5 4semaphore$h5 4sys6mman$h5
Functions to
create" open" or
delete
mq*open
mq*close
mq*unlink
sem*open
sem*close
sem*unlink
sem*init
sem*destroy
shm*open
shm*unlink
Functions !or
control
operations
mq*getattr
mq*setattr
!truncate
!stat
Functions !or
IPC operations
mq*send
mq*receive
mq*noti!y
sem*wait
sem*trywait
sem*post
sem*getvalue
mmap
munmap
Create i! it does not already
exist
exclusive create
O*C,7%
O*7XC/
O*C,7%
O*7XC/
O*C,7%
O*7XC/
&on#locking mode
runcate i! it already exists
O*&O&8/OC9
O*,:&C
% message queue can #e opened in any o! the three modes' read-only" write-only and
read-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 optional
O*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! it
already 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 on
an 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$
=
IPC Permissions
.hen creating new message queue" semaphore" or shared memory o#)ect at least one
additional argument is required" called mode$
his argument speci!ies the permission #its and is !ormed as the #itwise ; O, o! the
constants$
Constant Description
S*IS:S,
S*I.:S,
:ser read
:ser write
S*I,>,P
S*I.>,P
>roup read
>roup write
S*I,O3
S*I.O3
Other read
Other write
hese constants are de!ined in 4sys6stat$h5 header$
.henever an access to IPC o#)ect is requested !ollowing testing is per!ormed
I! the e!!ective user I+ o! the process is <" access is allowed$
does o#)ect
already exist
%re the access
permission O9?
System ta#les !ull?
O*C,7% set?
&ew o#)ect
is created
%re #oth O*C,7%
and O*7X7/ set?
7xistin
o#)ect
is re!$
@
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 is
denied$
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 access
permission #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 process
does 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 adequate
permission 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! the
pipe 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 highest
priority" 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 thread
when 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
mq_open() ; Creates a new message queue or opens an existing message queue$
Cinclude4mqueue$h5
mqd*t mq*openDconst char Ename" int o!lag" $ $ $
6E mode*t mode" struct mq*attr Eattr E6 FG
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 Iero$
mq_send() -- Places a message in the queue$
mq_receive() -- ,eceives DremovesF 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$
IPC' Semaphore
Semaphores are a programming construct designed #y 7$ .$ +i)kstra in the late 1JK<s$
% semaphore appears to #e a simple integer$ % process Dor a threadF waits !or permission
to proceed #y waiting !or the integer to #ecome <$ he signal i! it proceeds signals that
this #y per!orming incrementing the integer #y 1$ .hen it is !inished" the process changes
the semaphoreLs value #y su#tracting one !rom it$
M
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 <$
.ait !or a semaphore ; his tests the value o! the semaphore" waits i! the value is less
than or equal to <" and then decrements the semaphore value once it is greater than <$
his can #e summariIed #y the pseudocode$
whileDsemaphore*value4N<F
G 6E waitG i$e$ #lock the tread or processE6
semaphore*value--G
Post to a semaphore$ his increments the value o! the semaphore and can #e
summariIed #y the pseudocode
semaphore*value OOG
i! any processes are #locked" waiting !or this semaphores value to #ecome greater
than <" one o! the processes can now #e awoken$
here are other common names !or this operation' up" unlock and signal$
Common Posix Semaphore !unctions
sem_open() -- Connects to" and optionally creates" a named semaphore
sem_close() -- 7nds the connection to an open semaphore$
P,OC7SS % P,OC7SS 8
File system
process
kernel
8inary semaphore is a
!ile whose contents are
<61
Function to
create" wait and
post to
semaphore
K
sem_unlink() -- 7nds the connection to an open semaphore and causes the
semaphore to #e removed when the last process closes it$
sem_destroy() -- InitialiIes a semaphore structure Dinternal to the calling program"
so not a named semaphoreF$
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 queue is a simple one$
two Dor moreF processes can exchange in!ormation via access to a common system
message queue$ he sending process places via some DOSF message-passing module a
message onto a queue which can #e read #y another process DFigure =B$1F$ 7ach message
is given an identi!ication or type so 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 DremovesF 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$
P
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 occurs
in passing data #etween the processes$
SynchroniIation 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! synchroniIation ' 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 shared
memory 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 pathnameF " to either create a new shared
memory 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 diskF
synchroniIed with the memory mapped region in memory$ his !unction makes certain
that #oth copies synchroniIed$
shm*unlink ; removes the name o! a shared memory o#)ect$
!truncate ; to speci!y the siIe o! a newly created shared memory o#)ect or to change the
siIe 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
hree types o! IPC
System A message queue
System A semaphores
System A shared memory
are collectively known as RSystem A IPCS$ 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 or
open
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$
Cinclude4sys6ipc$h5
key*t !tok Dconst char Epathname" int idFG
returns' IPC key i! O9" -1 on error
his !unction takes in!ormation derived !rom the pathname and the low order Q #its o! id
and com#ines them into an integer IPC key$
3ere" the id argument is used to create multiple IPC channels o! same path name$ For
example" 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 which pathname 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 structure
he kernel maintains a structure o! in!ormation !or each IPC o#)ect" similar to the
in!ormation it maintains !or !iles
Cinclude4sys6ipc$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
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$F that create or open an IPC
o#)ect all takes an IPC key value 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 oflag argument that speci!ies the read-write
permission #its !or the IPC o#)ect and whether a new IPC o#)ect is #eing created or an
existing one is #eing re!erenced$
.e o#tain an IPC identi!ier !rom one o! the get !unction' msgget" semget" shmget$ hese
identi!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 same
message 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 were
small integers then the pro#a#ility o! !inding a valid identi!ier would #e a#out 1 in M<$
o avoid this pro#lem" the designers o! these IPC !acilities decided to increase the
possi#le range o! identi!ier to include all integers" not )ust small integers$
System A message 2ueue
System A message 2ueue are identi!ied #y a message queue identi!ier$ %ny process with
adequate privileges can place a message onto a given queue or read a message !rom a
given queue$
msgget !unction ; % new message queue is created" or an existing message queue is
accessed $
msgsnd !unction ; put a message string pointed #y its =
nd
argument on to the queue$
msgrcv !unction ; a message is read !rom a message queue using the msgrcv !unction$
msgctl !unction- provides a variety o! control operations on message queue$
/ike removing a queue !rom the system" setting and reading permission #its and mode$
Multiplexing messages
wo !eatures are provided #y the type !ield that is associated with each message on a
queue'
1
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 in
an order other than FIFO$
System A shared memory
Similar 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" #y
the shmget !unction$ he return value is an integer called the shared memory identifier.
hat is used with the three other shmXXX !unctions to re!er to this segment$
Cinclude4sys6shm$h5
int shm*getDkey*t key, siIe*t size, int oflagsFG
key can #e either a value returned #y !tok or the constant IPC*P,IA%7$
siIe ; speci!ies the siIe 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$ like
removing shared memory segment" setting permission #its and mode$
System A semaphore
he !unction semget() initialiIes 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+ DsemidF$
he key argument 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
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 the
procedure 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 descriptors can #e passed !orm the
client to the server$ 8oth data and descriptor can also #e passed #ack !rom the server to
the client$ +escriptor passing is inherent to doors$
Since doors are identi!ied #y descriptors" this allows a process to pass a door to other
process$
Basic API functions:
door*call !unction ; is called #y a client and it calls a server procedure that is executing
in the address space o! the server process$
Cinclude 4door$h5
int door*callDint fd,door*arg*t *argFG
returns' < i! ok " -1 on error
he descriptor !d is normally returned #y open$
he pathname opened #y the client !or identi!ier fd, identi!ies the server procedure to #e
called #y door*call$
he =
nd
argument 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
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 provides
communication between them by calling procedure of one another.
So in RPC, we code our application using the familiar procedure call( lie local procedure
call !, but the calling process(the client! and the process containing the procedure
being 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 their
arguments 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.$1.RS%
s#uare$out S+,-R.PR/C(s#uare$in! 2 ()&'
procedure number2('&
*2() &' version number '&
*23x4(543333)
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 is
received!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 networ
messages and vice7versa6 s#uare$xdr.c. xdr(external data
representation! 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<I.=> 'clnt$create(const char *host,unsigned long prognum, unsigned long versnum,
const char *protocol!)
Returns6 nonnull client handle if /?, =,<< on error.
host6 hostname or ip address of the host running our server.
1
prognum6 program name.
versnum6 version number.
protocol6 either >CP or ,8P.
>ypical code on client side main function6
C<I.=> 'cl)&& declaring client handle.
s#uare$in in)
s#uare$out 'outp)
cl2clnt$create(@(A5.(BC.(.(D,3x4(543333,(,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 the
second 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+,-R.PR/C, but from the client we
call s#uareproc$(. >he convension is that the name in the .x file is converted to
lowercase 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 automatically
generates the server main function.
name of the server must be $svc appended following the version number. >his allows
two -=SI C function prototypes in the generated .h header file, one for the
function called by the client and one for the actual server function.
Server procedure has two argument6
First is pointer to struct$in structure and
Second argument is a structure passed by the RPC runtime that contains information about
this 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.res(2 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
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 seleton
4! - client stub (that client program can use to send an RPC!
remoteproc$clnt.c
H! Internal function to convert the procedure parameters into networ
messages and vice7versa6 remoteproc$xdr.c
xdr(external data representation! must be shared by both server and
client.
Client needs with following files to compile6
(. client.c I client code, containing calling statement.
5. procedure$clnt.c I client stub(generated!
4. procedure$xdr.c I handles parameter and return value marshalling or
conversion
H. procedure.h I containing prototype of procedure that is called by client.
Server needs with following files to compile6
(! serverprocedure.c I contain actual remote procedure code.
5! procedur$xdr.c I shared by both client and server
4! procedure$svc.c I server stub
1
XI ;x6open transport inter!ace
XI 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
Cinclude4xti$h5
Cinclude4!cntl$h5
int t*openDconst char Epathname" int oflag" struct t*in!o EinfoFG
esta#lishes a communication end-point is to open the :&IX device that identi!ies the
particular 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
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 siIe in #ytes o! a protocol speci!ic address$ % value o! -1
indicates that there is no limit to the siIe$ For CP or :+P is siIe o! sockaddr*in
structure$
Options ; SiIe in #ytes o! protocol speci!ic !unctions$
tsdu ; stands !or Rtransport service data unitS$ his varia#le speci!ies the max siIe in
#ytes o! record whose #oundaries are preserved !rom one endpoint to other$ % value o! <
indicates that the communications provider doesnot support the concept o! a S+:$
For tcp value is always <" since CP provides a #yte stream service without any record
#oundary$
etsdu ; 7S+: stands !or Rexpedited transport service data unitS and this varia#le
speci!ies the max siIe in #ytes o! an 7S+:$ his is what we call out o! #and data$
connect ; some connection oriented protocols support the trans!er o! user data along with
a connection request$ his varia#le speci!ies the maximum amount o! this data$
CP doesnot support this !eature so its value is always -=$ and udp is not connection
oriented protocol" its value is also -=$
discon ; siIe o! the data that can #e passed along with a dis-connection request$
servtype ; his speci!ies the type o! service provided #y the communication provider $
*COS ; connection oriented service" without orderly release ex$ CP
*COS*O,+ - connection oriented service" with orderly release
*C/S ; connectionless service
flags ; additional !lag !or communication provider
*S7&+V7,O ; provider supports <-length writes
*O,+,7/+%% ; provider supports orderly release data
CP doesn(t support <-length writes #ut :+P does$
t_error and t_strerror functions
1
he xti !unctions normally return -1 on an error and set the varia#le t*errno to provide
additional in!ormation a#out the error$
t*errno is similar to errno in that it is set only when an error occurs and it is not cleared
on success!ul calls$
%ll error constants are de!ined 4xti$h5 and #egins with $
One special error constant is S0S7,, ; when it is returned in t*errno" it tells the
application to look at the value in errno !or the system error indication$
Functions to !ormat error messages
t_error and t_strerror
Cinclude4xti$h5
int t_errorconst char !msg"# returns:$
produces a message on the standard error output$ his message consist o! the string
pointed to #y msg !ollowed #y a colon and a space" !ollowed #y a message string
corresponding to the current value o! t*errno$ I! t*errno equals *S0S7,," then a
message is also output corresponding to the current value o! errno$
const char !t_strerrorint errno"# returns: pointer to message
returns a string descri#ing the value o! errnum" which is assumed to #e one o! the
possi#le t*errno values$ :nlike t*error" t*strerror does nothing special i! this value is
S0S7,,$
Net%uf structures and &'I structures
XI de!ines seven structures that are used to pass in!ormation #etween the application
and the XI !unctions$
One o! these is t*in!o descri#ed earlier$
he remaining six each contain #etween one and three net#u! structures$ he net#u!
structure de!ines a #u!!er that is used to pass data !rom the application to the XI
!unction and vice-versa$
struct net#u!T
unsigned int maxlenG6E max siIe o! #u!E6
unsigned int lenG 6E actual amount o! data in #u! E6
void E#u!G 6E data DcharE #e!ore posix$1g FE6
UG
!ollowing ta#le shows six structures that contain one or more net#u! structures" and the
various other mem#ers o! the XI structure$
+ataype t*#ind t*call t*discon t*optmgmt t*uderr t*unitdata
struct net#u!
struct net#u!
struct net#u!
addr addr
opt
udata udata
opt
addr
opt
addr
opt
udata
t*scalar*t
t*scalar*t
unsigned int glen
!lags
error
1
int
int
sequence
reason
sequence
Six XI structure and their mem#ers$
Since the address o! the net#u! structure is always passed to an Xti !unction and since the
structure contains #oth the siIe o! the #u!!er DmaxlenF and the amount o! data actually
stored in the #u!!er DlenF" there is no need in XI !or all the value arguments used in the
socket$
t_%ind function
his !unction assigns the local address to an endpoint and activates the endpoint$ In the
case o! CP or :+P the local address is an IP address and a port$
Cinclude4xti$h5
int t*#indDint fd,const struct t*#ind Erequest" struct t*#ind EreturnFG
returns ' < i! O9" -1 on error$
he second and third argument point to t*#ind structure
struct t*#indT
struct net#u! addrG6E protocol speci!ic address E6
unsigned int lenG 6EmaxC o! outstanding connection Di! serverFE6
UG
he endpoint is speci!ied #y fd. here are three cases to consider !or the request
argument$
request N N &://
the caller doesnot care what local address gets assigned to the endpoint$ he provider
selects an address$ he value o! glen argument is assumed to #e Iero$
request WNnull #ut request-5addr$len NN <
he caller doesn(t care what protocol address get assigned to the endpoint and again the
provider selects an address$ :nlike the previous case" the caller can now speci!y a
nonIero value !or the glen mem#er o! the request structure$
request WNnull and request-5addr$len 5 <
he caller speci!ies a local address !or the communication provider to assign to the
communication endpoint$
he value o! glen has meaning only !or connection oriented server' it speci!ies the
maximum num#er o! connection to queue !or this endpoint$
% connection oriented XI client must call t*#ind #e!ore calling t*connect$ his di!!ers
!rom connect" which calls #ind internally" i! the socket has not #ound$
t_connect function
% connection oriented client initiates a connection with a server #y calling t*connect$ he
client speci!ies the server(s protocol address$
Cinclude4xti$h5
int t*connectDint fd,const struct t*call Esendcall, struct t*call ErecvcallFG
he second and third arguments points to a t*call structure$
1
struct t*callT
struct net#u! addrG 6E protocol speci!ic addressE6
struct net#u! optG 6E protocol speci!ic address E6
struct net#u! udataG 6E user data to accompany conn$ request E6
int sequenceG 6E !or t*listen and t*accept !unction E6
UG
addr: speci!ies the server(s address$
opt: speci!ies the protocol speci!ic options desired #y the caller$
udata: %ny user data to #e trans!erred to the server during connection esta#lishment$
se(uence: It has no signi!icance !or this !unction #ut is used when this structure is used
with the t*accept !unction$
On return !rom this structure" the t*call structure pointed #y the recvcall argument
contains in!ormation associated with the connection that is returned #y the
communication provider to the caller$ he addr structure contains the address o! the peer
process" opt contains any protocol dependent options associated with the connection and
udata contains any user data returned #y the peers during connection esta#lishment$
Sequence num#er has no meaning$
8y de!ault" this !unction does not return until the connection is completed or an error
occurs$
.hen an error occurs during connection esta#lishment t*connect returns -1" #ut t*errno is
set to /OO9" requiring more code to determine exact reason$
t_rc) and t_snd function
8y de!ault" XI applications can(t call normal read and write !unctions$ Instead XI
applications must call t*rcv and t*snd$
Cinclude4xti$h5
int t*rcv Dint fd, void E#u!!" unsigned int n#ytes" int E!lagsFG
int t*sndDint fd, const void E#u!!" unsigned int n#ytes" int !lagsFG
#oth return' no o! #ytes read or written o! O9" -1 on error$
he !irst three argument are similar to !irst three argument to read or write' descriptor"
#u!!er pointer and num#er o! #ytes to read or write$
he !lags argument to t*snd is either Iero" or some com#ination o! the !ollowing
constants
*7XP7+I7+ ; send or receive expedited Dout o! #andF data$
*MO,7 ; there is no more data to send or receive$ his !lag is provided so that multiple
t*rcv or t*snd !unction calls can read or write what the protocol considers a logical
record$
XI response to FI& or ,S segment
.hen a CP FI& is received !or an XI endpoint" t*rcv returns -1 with t*errno
set to /OO9$ he XI !unction t*look must then #e called" and it returns
*O,+,7/$ his is called an orderly release indication.
=
.hen a CP ,S is received !or an XI endpoint" t*rcv returns -1 with t*errno
set to /OO9$ he XI !unction t*look must then #e called and it returns
*+ISCO&&7C$ his is called a disconnect or an abortive release.
t_loo* function
Aarious events can occur !or an XI endpoint and these events can occur
asynchronously$ 8y that we mean that the application can #e per!orming some task when
an related event occurs on the endpoint$ Many o! such event indicate with /OO9 error
constant assigned to t*errno$ %nd to get in!ormation a#out event occurred" one has to call
t*look on that endpoint$
Cinclude4xti$h5
int t*lookDint !dFG
return' event i! O9" -1 on error$
he integer value returned #y this !unction is one o! the nine events shown here$
7vent +escription
*CO&&7C
*+%%
*+ISCO&&7C
*7X+%%
*>O+%%
*>O7X+%%
*/IS7&
*O,+,7/
*:+7,,
Connection con!irmation received
&ormal data received
+isconnect received
7xpedited data received
Flow control restriction on normal data li!ted
Flow control restriction on expedited data li!ted
Connection indication received
Orderly release indication received
7rror in previously sent datagram$
t_sndrel and t_rc)rel function
XI supports two ways o! releasing a connection' an orderly release and an a#ortive
release$ he di!!erences are that an a#ortive release does not guarantee the delivery o!
any outstanding data" while the orderly release guarantee this$
.e can send and receive an orderly release with the !ollowing !unctions'
Cinclude4xti$h5
int t*sndreiDint fdFG
int t*rcvrelDint fdFG
#oth return'< i! O9" -1 on error$
% process issues an orderly release #y calling t*sndrel$ his tells the provider that the
application has no more data to send on this endpoint$ For a CP endpoint" CP sends a
FI& to the peer$ he process that calls t*sndrel can continue to receive data" #ut it can no
longer write to the descriptor$
=
% process acknowledges the receipt o! a connection release #y calling the t*rcvrel
!unction$ his process can still write to the descriptor #ut it can no longer read !rom the
descriptor$
t_snddis and t_rc)dis function
he !ollowing two !unctions handle an a#ortive release
Cinclude4xti$h5
int t*snddisDint fd" const struct t*call EcallFG
int t*rcvdisDint fd" struct t*discon EdisconFG
8oth return' < i! ok " -1 on error$
he t*snddis !unction is used !or two di!!erent purposes'
o per!orm an a#ortive release o! an existing connection" which in terms o! CP
causes an ,S to #e sent " and
o re)ect a connection request$
For an a#ortive release o! an existing connection" call argument can #e a null pointer$
.hen a *+ISCO&&7C event occurs on an XI endpoint De$g$ an ,S is received on
CPF" the application must receive the a#ortive release #y calling t*rcvdis$ I! the discon
argument is a nonnull pointer" a t*discon structure is !illed in with the reason !or the
a#ortive release$
struct t*disconT
struct net#u! udataG 6Euser dataE6
int reasonG6E protocol speci!ic reason code E6
int sequenceG 6Eapplica#le only !or server receiving connection E6
UG
&'I and Soc*et interopera%ility
he interopera#ility is provided #y the internet protocol suite and has nothing to do with
socket or XI$% client written using CP or :+P interoperates with a server using the
same transport protocol i! the client and server speak the same application protocol.
,egardless o! what %PI is used to write either the client or the server$ It is the protocol
that determine the interopera#ility not the %PI we use to write the server and client$
&'I Name and address con)ersion functions
he network services li#rary provides numerous !unctions to read the netcon!ig !ile$
he setnetcon!ig !unction opens the !ile and the !unction getnetcon!ig then read the next
entry in the !ile$ endnetcon!ig closes the !ile and releases any memory that was allocated$
Cinclude 4netcon!ig$h5
void Esetnetcon!igDvoidFG
returns- nonnull pointer i! O9" &:// on error
struct netcon!ig Egetnetcon!igDvoid EhandleFG
returns' nonnull pointer i! O9" &:// on end o! !ile$
int endnetcon!igDvoid EhandleFG
return' < i! O9" -1 on error$
he pointer returned #y setnetcon!ig is then used as the argument to the remaining two
!unctions$ 7ach entry in the !ile is returned as a netcon!ig structure$
struct netcon!igT
char nc*netidG 6EStcpS"SudpS" etc$ E6
=
unsigned long nc*semanticsG 6E&C*PI*C/S" etc$ E6
unsigned long nc*!lagG6E &C*AISI8/7" etc$ E6
char Enc*proto!mlyG6ESinetS" Rloop#ackS" etc$ E6
char Enc*protoG6EStcpS"SudpS" etc$ E6
char Enc*deviceG6Edevice name !or network id E6
unsigned long nc*nlookupsG 6E C o! entries in nc*lookups E6
char nc*lookupsG 6E list o! lookup li#raries E6
unsigned long nc*unusedXQYG
UG
+,ample using netconfig
void EhandleG
struct netcon!ig EncG
handle N setnetcon!igDFG
whileDDnc N getnetcon!igDhandleFFWN&://F
6E print netcon!ig structure E6
U
endnetcon!igDhandleFG
N+'PA'- )aria%le and netpath .unctions
he getnetcon!ig !unction returns the next entry in the !ile" letting us go through the
entire !ile line #y line$ 8ut !or interactive programsDtypicallyF we want the searching o!
the !ile limited only to the protocols that the user interested in$
his is done #y allowing the user to set an environment varia#le named &7P%3 and
then using the !ollowing !unctions instead o! the netcon!ig !unctions descri#ed in the
process section$
Cinclude4netcon!ig$h5
void Esetnetcon!igDvoidFG
,eturns' nonnull pointer i! O9" &:// on error
struct netcon!ig EgetnetpathDvoid EhandleFG
,eturns' nonnull pointer i! O9" &:// on end o! !ile$
int endcon!igDvoid EhandleFG
,eturns' < i! O9" -1 on error
For example" we could set the environment varia#le with the shell as
export &7P%3N udp'tcpG
with this setting" i! we coded our program as shown
void EhandleG
struct netcon!ig EncG
handle N setnetcon!igDFG
whileDnc N getnetcon!igDhandleFFWN&://FT
6E print net con!ig structure E6
U
only two entries would #e printed" one !or :+P !ollowed #y one !or CP$ he order o!
the two structure returned now corresponds to the order o! the protocols in the
environment varia#le" and not to the order in the netcon!ig !ile$
I! the &7P%3 environment varia#le is not set" all visi#le entries are
returned" in the order in the netcon!ig !ile$
=
Netdir .unctions
he netcon!ig and netpath !unctions let us !ind a desired protocol$ .e also need to look
up a hostname and a service name" #ased on the protocol that we choose with the
netcon!ig and netpath !unctions$ his is provided #y the netdir*get#yname !unction$
Cinclude4netdir$h5
int netdir*get#ynameDconst struct netcon!ig Encp"
const struct nd*hostsery Ehsp"
struct nd*addrlist EEalppFG
returns' < i! O9" non-Iero on error
void netdir*!reeDvoid Eptr" int typeFG
we have to pass host name and service name in the nd*hostsery structure as second
argument$
struct nd*hosteryT
char Eh*hostG
char Eh*servG
UG
he third argument points to a pointer to an nd*addrlist structure and on
success Ealpp contains a pointer to one o! these structures'
struct nd*addrlistT
int n*cntG6E no o! net#u!!s E6
struct net#u! n*addrsG / array o! net#u!!s containing the addrs E6
UG
this nd*addrlist structure points to an array o! one or more net#u! structures" each o!
which contains one o! the host address and are dynamically allocated$
o this dynamically allocated array o! nd*addrlist structure" we call netdir*!ree with ptr
pointing to the nd*addrlist structure and type set to &+*%++,/IS$
he reverse conversion- given a net#u!! structure containing an address" return
the host name and service name ; is provided through netdir*get#yaddr$
Cinclude4netdir$h5
int netdir*get#yaddrD const struct netcon!ig Encp"
struct nd*hostservlist Ehslpp"
const struct net#u! EaddrFG
,eturns' < i! O9" nonIero on error
he result is a pointer to an nd*hostservlist structure and this pointer is stored in Ehslpp$
Struct nd*hostservlistT
int h*cntG6E num#er o! hostservs E6
struct nd*hostsery h_hostser)s# /E the hostname6service name pairs E6
UG
this structures is allocated dynamically and must #e !reed #y calling netdir*!ree with the
type o! &+*3OSS7,A/IS$
t_alloc and t_free function
%s we have seen previously with XI there are six structures each o! which contains one
ore more net#u! structures$ he net#u! structures points to a #u!!er whose siIe depends
on the siIe o! the protocol address$ o simpli!y the dynamica memory allocation o! these
XI structures and the net#u! structures that they contain" t*alloc and t*!ree are provided$
=
Cinclude4xti$h5
void Et*allocDint !d" int structtype" int !ieldsFG
returns' nonnull pointer i! O9" &:// on error
int t*!reeDvoid Eptr" int structtypeFG
returns' < i! O9" -1 on error$
he struct type argument speci!ies which o! the seven XI structures is to #e allocated
or !reed and must #e one o! the constants shown here
he !ields argument let us speci!y that space !or one or more net#u! strucutures should
alos #e allocated and initialiIed$
!ields is the #itwise O, o! the constants shown here
he intent o! XI model is to allow the transport layer to tell the server process when a
S0& arrives !rom a client$
Struct type ype o! structure
*8I&+
*C%//
*+IS
*I&FO
*OPM>M
*:+7,,O,
*:&I+%%
Struct t*#ind
struct t*call
struct t*dis
struct t*in!o
struct t*optmgmt
struct t*uderr
struct t*unitdata
Fields %llocate and initialiIe
*%//
*%++,
*OP
*:+%%
%ll relevant !ields o! the structure
addr !ield o! t*#ind" t*call
opt !ield o! t*optmgmt" t*call
udata !ield o! t*call" t*discon or t*unitdata$
t*getprotaddr !unction
returns #oth the local and !oreign protocol address associated with an endpoint$
Cinclude4xti$h5
int t*getprotaddrDint !d" struct t*#ind Elocaladdr" struct t*#ind EpeeraddrFG
returns' < i! O9" -1 on error$
he address is returned in addr mem#er D net#u! structureF o! two t*#ind structure$
'CP Ser)er using &'I
XI model allows the transport layer to tell the server process when a S0& arrives"
passing client protocol address$ he server process is then allowed to send either accept
or re)ect the request$ The server's TC !ould not send its "#$%&C' or ("T until the
server process tells it !hat to do.
=
$otice the server' function calls)
t*bind + indicates that end point !ill be accepting connection
t*listen + returns !hen connection is available.
t*accept + to accept the connection
t*snddis + to re,ect the request.
t*listen !unction
Cinclude4xti$h5
int t*listenDint fd, struct t*call *callFG
returns' < i! O9" -1 on error
struct t*callT
struct net#u! addrG
struct net#u! optG
struct net#u! udataG
int sequenceG
UG
he structure returned through the call pointer contains relevant parameters o! the
connection'
addr' contains the protocol address o! the client$
Opt' contains any protocol speci!ic address$
:data' contains any user data sent along with connection request$
Sequence' contains unique value that identi!ies this connection request$this value will #e
used when we call t*accept or t*snddis to identi!iy which connection to accept or re)ect$
t_accept function
Once the t*listen !unction indicates that a connection has arrived" we choose whether to
accept the request or not$ o accept the request the t*accept is called
Cinclude4xti$h5
int t*accept D int listen!d" int conn!d" struct t*call EcallFG
returns' < i! O9" -1 on error$
=

Anda mungkin juga menyukai