Ipc by sreekanthreddy


Interview questions and carreir developmwnt concept study materials,some tutorials

More Info
									                               Interprocess Communication


Pipe is a mechanism to communicate and share data between two processes. The data flows from
one process to another. Data flows only in one direction. The pipe is only between processes that
have a common ancestor Generally it is done by attaching the output of one process to the input
of another.

A pipe is created by calling the „pipe‟ function.

   #include <unistd.h>
   int pipe ( int fd[2] );
       Returns: 0 if ok, -1 on error

Two file descriptors are returned: fd[0] is open for reading and
                                   fd[1] is open for writing

           User Process
        fd[0]    fd[1]


A pipe in a single process is next to useless. Therefore it is IPC channel from parent to child or
vice versa

   PARENT                               CHILD

fd[0]      fd[1]                       fd[0]    fd[1]



For a pipe from the parent to the child:
            parent closes the read end of the pipe fd[0]
            child closes the write end of the pipe fd[1]
For a pipe from the child to the parent:
            parent closes the write end of the pipe fd[1]
            child closes the read end of the pipe fd[0]

If multiple processes are writing to a pipe descriptor and we write more than PIPE_BUF bytes
(kernel‟s Pipe buffer size), the data might be interleaved with the data from the other writers.

popen & pclose for pipes

The standard I/O library provides a function that creates a pipe and initiates another process that
either reads from the pipe or writes to the pipe.

#include <stdio.h>
FILE *popen( const char *Cmdstring, const char *type);
                Returns fp if ok, NULL on error.
       If type is “r”, the fp is connected to the stdout of Cmdstring
       If type is “w”, the fp is connected to the stdin of Cmdstring.
int pclose ( FILE *fp);
       Returns termination status of Cmdstring, or -1 on error.

Named Pipes: FIFOs

FIFO stands for First In, First Out. A FIFO is similar to Pipe. It is a one way flow of data, with
the first byte written to it being the first byte read from it. Unlike pipes, a FIFO has a name
associated with it, allowing exchange of data between „unrelated‟ processes. FIFOs are also
called named Pipes.

Creating FIFOS using command line program

 $ mknod    filename p (or)
 $ mkfifo   filename
 $ cat       < filename &
 $ echo     “hello” > filename

Creating FIFOs from inside a program

# include < sys/types.h >
# include < sys/stat.h >

int mkfifo( const char *filename, mode_t mode );
int mknod ( const char *filename, mode_t mode | S_IFIFO, ( DEV_T)0);

A FIFO exists as a named file, not as an open file descriptor, and must be opened before it can be
read from or written to.

open ( const char *path, O_RDONLY);
        Open blocks until a process opens the same FIFO for writing
open ( const char *path, O_RDONLYIO_NONBLOCK);
        Open succeeds and returns immediately, even if the FIFO had not been opened
        for writing by any process
open ( const char *path, O_WRONLY);
        Open blocks until a process opens the same FIFO for reading.
Open ( const char *path, O_WRONLY | O_NONBLOCK);
       returns –1 and the FIFO not opened, if no process has the FIFO open for reading

A read on an empty blocking FIFO will wait until some data can be read.

A read on a non-blocking FIFO with no data will return „0‟ bytes.

A write on a full blocking FIFO will wait until data can be written.

System V IPC

A mechanism to communicate and share data among multiple running processes. The three types
of IPC:
        Message queues
        Shared memory
Are collectively referred to as “System V IPC”. A summary of these systems is shown in the
following table:

                              Message queue           Semaphore           Shared memory
Include file                  <sys/msg.h>             <sys/sem.h>         <sys/shm.h>
System call to create or      Msgget                  semget              shmget
System call for control       Msgctl                  semctl              shmctl
Systems calls for IPC         Msgsnd                  semop               shmat
operations                    Msgrcv                                      shmdt

The kernel maintains a structure of information for each IPC channel, similar to the information
it maintains for files. This structure and other manifest constants are defined in <sys/ipc.h>. The
three ctl system calls are used to access this structure and modify it.

key_t Keys

The function ftok() is provided by System V standard C library to convert a path name and
project identifier into a System V IPC key. These system V keys are used to identify message
queues, shared memory, and semaphores.

       #include <types.h>
       #include <sys/ipc.h>

       key_t ftok(char *pathname, char proj);

The key_t data type is a 32bit integer.
The path name could be path of common data file name, server name or other path name in the
The proj argument is an 8-bit character

Message Queues

Message queues are linked list of messages stored within a kernel and identified by a message
queue identifier. Message queue provides a way of sending a block of data from one process to
another along with a type.

The message queue function definitions are:

int msgget ( key_t key, int msgflg ) ;

int msgsnd ( int msgid , const void *msg_ptr, size_t msg_sz, int msgflg) ;

int msgrcv ( int msgid , void *msg_ptr, size_t msg_sz, long int msgtype, int msgflg ) ;

int msgctl ( int msgid , int cmd, struct msgid_ds *buff);


A semaphore is a special variable that takes only whole numbers and upon which only two
operations are allowed: „Wait‟ and „Signal‟
        P ( Semaphore variable ) for wait.
        V ( Semaphore variable ) for signal.
All the UNIX Semaphore functions operate on arrays of general semaphores.

semget: The semget funtion creates a new Semaphore or obtains the semaphore key of an
existing semaphore

int semget ( key_t key, int num_sems, int sem_flags);

key : is an integral value used to allow unrelated processes to access the same semaphore.

num_sems: number of semaphores required

sem_flags: lower nine bits are the permissions for the semaphore ( similar to file
            permissions) and other flags are IPC_CREAT, IPC_EXCL
Returns Semaphore id ( a +ve integer) or –1 on error.
semop : The function semop is used for changing the value of the semaphore

int semop ( int semid, struct sembuf *sem_ops, size_t num_sem_ops);

sem_id : Semaphore identifier, as returned from semget

sem_ops : a pointer to an array of structures of type „sembuf‟
struct sembuf {
          short sem_num ; //semaphore number( starts with 0 )
          short sem_op ; // Value by which the semaphore should be changed
          short sem_flg;     // operation flags

semctl : The semctl function allows direct control of semaphore information.

int semctl ( key_t , int num_sems, int sem_flags);

num_sem_ops: number of operations

union semun {
             int val;
             struct semid_ds *bf ;
             unsigned short     *array;
Commands: IPC_RMID Remove the semaphore set.
          GETALL      get „semval‟ for all semaphores of the set
          GETVAL       get „semval‟ of nth semaphore
          SETVAL       set „semval‟ for all the semaphores of the set to „val‟

Shared Memory

Allows two unrelated processes to access the same logical memory. Very efficient way of
transferring data between running processes .If one process write to the shared memory the
changes immediately become visible to any other process that has access to the same shared

Synchronizing the access is the responsibility of the programmer. The functions for creating and
handling shared memory:

            # include < sys / shm.h >
            int shmget ( key_t key , size_t size, int shmfld ) ;
             void *shmat ( int shm_id , const void *shm_addr, int shmflg ) ;
            int shmdt ( const void *shm_addr ) ;
            int shmctl ( int shm_id , int cmd, struct shmid_ds *buf );


To top