You are on page 1of 14

Interprocess Communication (IPC) In numerous applications there is clearly a need to communicate among the multiple running processes, with

each exchanging data or control information. There are a few methods which can accomplish this task:

Pipes ignals ystem ! IPC

"essage #ueues emaphores hared "emory

Pipes Pipes are a simple synchroni$ed way of passing information %etween two processes. & pipe can %e 'iewed as a special file that can store only a limited amount of data and uses a (I() access scheme to retrie'e data. In a logical 'iew of a pipe, data is written to one end and read from the other. Pipes come in two 'arieties: *nnamed: *nnamed pipes can only %e used %y related processes (i.e. a process and one of its child processes, or two of its children). *nnamed pipes cease to exist after the processes are done using them. +amed: +amed pipes exist as directory entries, complete with permissions. This means that they are persistent and that unrelated processes can use them. Piping in a C program: ,stdio.h.e must first open a pipe /0I+*1 allows two ways of opening a pipe. pipe() 22 0ow le'el Piping
1

int pipe(int fd[2]) 22 creates a pipe and returns two file descriptors, fd[0], fd[1]. fd[0] is opened for reading, fd345 for writing. pipe() returns 6 on success, 24 on failure and sets errno accordingly. The standard programming model is that after the pipe has %een set up, two (or more) cooperati'e processes will %e created %y a fork and data will %e passed using read() and write(). Pipes opened with pipe() should %e closed with close(int fd). 7xample: #define DATA "hello world" #define BUFFSIZE 1024 int rgfd[2] !" file de#$ri%tor# of #tre&'# "!

!" () E**)* +,E+-I(./ I00UST*ATI)( )(0122222 "! '&in34 5 $h&r #6B7f[BUFFSIZE] %i%e3rgfd4 if 3for8344 5 !" %&rent/ re&d fro' %i%e "! $lo#e3rgfd[1]4 !" $lo#e write end "! re&d3rgfd[0]/ #6B7f/ BUFFSIZE4 %rintf3"99:;#<n"/ #6B7f4 $lo#e3rgfd[0]4 = el#e 5 !" $hild/ write d&t& to %i%e "! $lo#e3rgfd[0]4 !" $lo#e re&d end "! write3rgfd[1]/ DATA/ #i>eof3DATA44 $lo#e3rgfd[1]4 e?it304 =
2

FIFO A FIFO is similar to a pipe. A FIFO (First In First Out) is a one-way flow of data. FIFOs a!e a name, so unrelated pro"esses "an s are t e FIFO. FIFO is a named pipe. # is is t e main differen"e $etween pipes and FIFOs. %reate& A FIFO is "reated $y t e m'fifo fun"tion& (in"lude )sys*types. + (in"lude )sys*stat. + int m'fifo("onst " ar ,pat name, mode-t mode). pat name / a 0I123 pat name (pat and filename). # e name of t e FIFO mode / t e file permission $its.

Open& m'fifo tries to "reate a new FIFO. If t e FIFO already e4ists, t en an 553I6# error is returned. #o open an e4istin7 FIFO, use open(), fopen() or freopen()

%lose& to "lose an open FIFO, use "lose(). #o delete a "reated FIFO, use unlin'(). 8roperties& ( 6ome of t em are also appli"a$le to 8I856) 1) After a FIFO is "reated, it "an $e opened for read or write. 2) A read 7ets as mu" data as it re9uests or as mu" data as t e FIFO as, w i" e!er is less.

:) A write to a FIFO is atomi", as lon7 as t e write does not e4"eed t e "apa"ity of t e FIFO. # e "apa"ity is at least ;' . ;) <lo"'ed if read from an empty FIFO, or write to a full FIFO. IPC:"essage #ueues:@#A#!'#gBh: The %asic idea of a message queue is a simple one. Two (or more) processes can exchange information 'ia access to a common system message 8ueue. The sending process places 'ia some () ) message2 passing module a message onto a 8ueue which can %e read %y another process. 7ach message is gi'en an identification or tA%e so that processes can select the appropriate message. Process must share a common 8eA in order to gain access to the 8ueue in the first place.

9asic "essage Passing IPC messaging lets processes send and recei'e messages, and 8ueue messages for processing in an ar%itrary order. *nlike the file %yte2stream data flow of pipes, each IPC message has an explicit length. "essages can %e assigned a specific type. 9ecause of this, a ser'er process can direct message traffic %etween clients on its 8ueue %y using the client process PI: as the message
4

type. (or single2message transactions, multiple ser'er processes can work in parallel on transactions sent to a shared message 8ueue. 9efore a process can send or recei'e a message, the 8ueue must %e initiali$ed (through the '#gget function see %elow) )perations to send and recei'e messages are performed %y the '#g#nd34 and'#gr$C34 functions, respecti'ely. .hen a message is sent, its text is copied to the message 8ueue. The '#g#nd34 and '#gr$C34 functions can %e performed as either %locking or non2%locking operations. +on2%locking operations allow for asynchronous message transfer 22 the process is not suspended as a result of sending or recei'ing a message. In %locking or synchronous message passing the sending process cannot continue until the message has %een transferred or has e'en %een acknowledged %y a recei'er. IPC signal and other mechanisms can %e employed to implement such transfer. & %locked message operation remains suspended until one of the following three conditions occurs:

# e "all su""eeds. # e pro"ess re"ei!es a si7nal. # e 9ueue is remo!ed.

Initialising the "essage #ueue The '#gget34 function initiali$es a new message 8ueue: int '#gget38eADt 8eA/ int '#gflg4 It can also return the message 8ueue I: ('#Eid) of the 8ueue corresponding to the key argument. The 'alue passed as the '#gflg argument must %e an octal integer with settings for the 8ueue;s permissions and control flags. The following code illustrates the '#gget34 function. #in$l7de @#A#!i%$Bh: #in$l7de @#A#!'#gBh: BBB
5

8eADt 8eA !" 8eA to 6e %&##ed to '#gget34 "! int '#gflg !" '#gflg to 6e %&##ed to '#gget34 "! int '#Eid !" ret7rn C&l7e fro' '#gget34 "! BBB 8eA F BBB '#gflg F BBB '#Eid F '#gget38eA/ '#gflg4 ending and <ecei'ing "essages The '#g#nd34 and '#gr$C34 functions send and recei'e messages, respecti'ely: int '#g#nd3int '#Eid/ $on#t Coid "'#g%/ #i>eDt '#g#>/ int '#gflg4 int '#gr$C3int '#Eid/ Coid "'#g%/ #i>eDt '#g#>/ long '#gtA%/ int '#gflg4 The '#Eid argument must %e the I: of an existing message 8ueue. The '#g% argument is a pointer to a structure that contains the type of the message and its text. The structure %elow is an example of what this user2 defined %uffer might look like: #tr7$t 'A'#g 5 long 'tA%e $h&r 'te?t[GS.SZ] "! = !" 'e##&ge tA%e "! !" 'e##&ge te?t of length GS.SZ

The '#g#> argument specifies the length of the message in %ytes.The structure mem%er '#gtA%e is the recei'ed message;s type as specified %y the sending process.The argument '#gflg specifies the action to %e taken if one or more of the following are true:

# e num$er of $ytes already on t e 9ueue is e9ual to '#gDE6Ate#. # e total num$er of messa7es on all 9ueues system-wide is e9ual to t e system-imposed limit.

*pon successful completion, the following actions are taken with respect to the data structure associated with '#Eid:
o o

'#gDEn7' is in"remented $y 1. '#gD#ti'e is set e9ual to t e "urrent time.

FI05 A%%566 I1 % 1=.>.1. A""ess 6ystem %all

# e a""ess system "all determines w et er t e "allin7 pro"ess as a""ess permission to a file. access() " e"'s t e named file its e4isten"e and also for a""essi$ility a""ordin7 to modeB # e synta4 of t e "all is 7i!en $elow& int access(char *path, int mode) Ar7uments are& path points to a pat name namin7 a file. mode, Four types of mode are defined in #include <unistd.h>: ?-O@ - test for read permission A-O@ - test for write permission 3-O@ - test for e4e"ute or sear" permission F-O@ - test w et er t e dire"tories leadin7 to t e file "an $e sear" ed and t e file e4ists. On su""ess access() returns 0, it means t e pro"ess as all t e spe"ified permissions, and -1 on failure and sets errno to point t e
7

error ( for e4ample errno is set to 5?OF6, if write permission was re9uested for a file on a read-only file system or set to 5A%%56 if a dire"tory in t e file pat is ina""essi$le). If t e se"ond ar7ument is F-O@, a""ess simply " e"'s for t e fileBs e4isten"e. If t e file e4ists, t e return !alue is 0. if not, t e return !alue is /1 and errno is set to 51O51#.

54ample 1=.: uses a""ess "all to " e"' for a fileBs e4isten"e and to determine or " e"' t e permissions on a file t at is spe"ified as t e "ommand line ar7ument to t e pro7ram. (in"lude )errno. + (in"lude )stdio. + (in"lude )unistd. + int main (int ar7", " ar, ar7![]) C " ar, pat D ar7![1]. int e4ists. e4ists D a""ess (pat , F-O@). *,% e"'in7 fileBs e4isten"e.,* if (e4ists DD 0) printf (EFs e4ists in t e systemGnH, pat ). else C if (errno DD 51O51#) printf (EFs does not e4ists in t e systemGnH, pat ).
8

else if (errno DD 5A%%56) printf (E# e dire"tory of Fs does not permissionGnH, pat ). return 0. I e4ists D a""ess (pat , ?-O@). if (e4ists DD 0) printf (EFs as read a""essGnH, pat ). else printf (EFs a""ess deniedGnH, pat ). e4ists D a""ess (pat , A-O@). *, #o " e"' write permission. ,* if (e4ists DD 0) printf (EFs as an a""ess to writeGnH, pat ). else if (errno DD 5A%%56) printf (EFs as no a""ess to writeGnH, pat ). else if (errno DD 5?OF6) printf (EFs as no write a""essGnH, pat ). return 0. I Example 16.3 Program to Chec (access$chec ) !ccess Permissions o" a #ile a!e a""ess

?unnin7 e4ample 1=.:, to " e"' a""ess permissions for a file named 62JI# on a pendri!e, in!o'e it li'e t is& [sumsKlo"al ost sums]L .*access$chec mnt*pendri!e*62JI# e4ists in t e system mnt*pendri!e*62JI# as read a""ess mnt*pendri!e*62JI# as no write a""ess 4=.=. C&++I+> &+: )<TI+> :I<7CT)<I7 : ,sys?types.h-,,sys?dir.hThere are two 'ery useful functions a'aila%le on 9 : platforms and not in multi2threaded applications. Those are: 4=.=.4 The scandir() function The scandir() function returns the num%er of entries in the array, and stores a pointer to the array in the location referenced %y namelist. The function call of scandir() is gi'en as: scandir(char *dirname, struct dirent **namelist, int (*select)(), int (*compar)()) Ar7uments of t e fun"tion are& dirname # e name of t e dire"tory t at you want to s"an. namelist A pointer to a lo"ation w ere scandir() "an store a pointer to t e array of dire"tory entries t at it $uilds. select A pointer to a user-supplied su$routine t at scandir() "alls to sele"t w i" entries to in"luded in t e array. # e select routine is
10

*mnt*pendri!e*62JI#

passed a pointer to a dire"tory entry and s ould return a nonMero !alue if t e dire"tory entry is to $e in"luded in t e array. If select is 1200, all t e dire"tory entries are in"luded. compar A pointer to a user-supplied su$routine t atNs passed to %sort() to sort t e "ompleted array. If t is pointer is 1200, t e array isnNt sorted. Oou "an use alphasort() as t e compar parameter to sort t e array alp a$eti"ally. ?eturn Palue # e scandir() fun"tion returns t e "urrent dire"tory (.) and its parent dire"tory (..) as well as all file entries in t e sele"ted dire"tory or -1 if an error o""urs. scandir and alphasort a!e definitions in s&s't&pes.h and s&s'dir.h. (!)P!*+,E- and get.d definitions in s&s'param.h. 1=.Q.FI05 JA1I820A#IO1 ?O2#I156& unistd.h/ s&s't&pes.h/ s&s'stat.h # ere are many system "alls t at "an applied dire"tly to files stored in a dire"tory. 1=.Q.1. % e"'in7 File 6tatus

#wo useful fun"tions e4ist to in9uire a$out t e files "urrent status. Oou "an find out ow lar7e t e file is (st$si0e)/ w en it was "reated (st$ctime) etc. # e two fun"tions are prototyped in <s&s'stat.h> int stat(char *path, struct stat *buf), int fstat(int filedes, struct stat *buf)
11

stat() o$tains information a$out t e file named $y pat . ?ead, write or e4e"ute permission of t e named file is not re9uired, $ut all dire"tories listed in t e pat name leadin7 to t e file must $e sear" a$le. "stat() o$tains t e same information a$out an open file referen"ed $y t e file des"riptor passed as an ar7ument "iledes, su" as would $e o$tained $y an open "all. stat()/ &nd "stat() return 0 on su""ess, -1 on failure and sets errno to indi"ate t e error. 5rrors are a7ain defined in #include <s&s'stat.h> 1u" is a pointer to a stat stru"ture into w i" information is pla"ed "on"ernin7 t e file. A stat stru"ture is defined in #in$l7de )sys*types. +B ?eturn Palues On su""essful e4e"ution, 0 is returned. Ot erwise, R1 is returned and errno is set to indi"ate t e error. # e followin7 e4ample s ows ow to o$tain file status information for a file named * ome*sumit*stat1. # e stru"ture !aria$le $uffer is defined for t e stat stru"ture. !inc"ude #s$s%t$pes&h' !inc"ude #s$s%stat&h' struct stat buffer int status &&& status ( stat()%home%sumit%stat1), *buffer) 1=.Q.2 2sin7 remo!e()
12

# e remo2e() fun"tion "auses t e file or empty dire"tory w ose name is t e strin7 pointed to $y path to $e no lon7er a""essi$le $y t at name. 6u$se9uent attempts to open t at file usin7 t at name will fail, unless t e file is "reated anew. # e fun"tion "all of remo2e() is 7i!en as& !inc"ude #stdio&h' int remo+e(const char *path) For files, remo2e() is identi"al to unlin (). For dire"tories, remo2e() is identi"al to rmdir(). On su""ess, remo2e() returns 0.Ot erwise, it returns R1 and sets errno to indi"ate an error. 2sin7 rename(), renameat() !inc"ude #unistd&h' int rename(const char *old, const char *new) !inc"ude #unistd&h' int renameat(int fromfd, const char *old, int tofd, const char *new) # e rename() fun"tion " an7es t e name of a file. # e old ar7ument points to t e pat name of t e file to $e renamed. # e ne. ar7ument points to t e new pat name of t e file. # e renameat() fun"tion renames an entry in a dire"tory, possi$ly mo!in7 t e entry into a different dire"tory. If t e old ar7ument is an a$solute pat , t e "rom"d is i7nored. Ot erwise it is resol!ed relati!e to t e "rom"d ar7ument rat er t an t e "urrent wor'in7 dire"tory. 6imilarly, if t e ne. ar7ument is not a$solute, it is resol!ed relati!e to t e to"d ar7ument.

13

If old and ne. $ot refer to t e same e4istin7 file, t e rename() and renameat() fun"tions return su""essfully and performs no ot er a"tion. 2pon su""essful "ompletion, t e rename() and renameat() fun"tions will mar' for update t e st$ctime and st$mtime fields of t e parent dire"tory of ea" file. 2pon su""essful "ompletion, 0 is returned. Ot erwise, R1 is returned and errno is set to indi"ate an error. 1=.Q.;. 2sin7 unlin'() # e unlin () fun"tion remo!es a lin' to a file. # e fun"tion "all of unlin () is 7i!en as& !inc"ude #unistd&h' int un"in,(const char *path) If path names a sym$oli" lin', unlin () remo!es t e sym$oli" lin' named $y path and does not affe"t any file or dire"tory named $y t e "ontents of t e sym$oli" lin'. Ot erwise, unlin () remo!es t e lin' named $y t e pat name pointed to $y path and de"rements t e lin' "ount of t e file referen"ed $y t e lin'.

14

You might also like