Wednesday, February 27, 2013

IPC Using PIPE Mechanism

IPC - Stands for Inter Process Communication

PIPE - There are different mechanisms to achieve IPC, one of them is PIPE. Other IPC mechanisms are Message passing, shared Memory and semaphores. To understand PIPE concept please see the following pic.



Fork()- This function is used to create parent and child process. Fork returns 2 times. 1st time it returns 0 in child process, 2nd time it returns 1 in parent process.

See the following code where child and parent process do IPC using PIPE concept. The child process waits for a key press, and then informs the parent process about it. The parent process waits for this information and then exits.


/* program to demonstrate usage of pipes */

#include <stdio.h>
// unistd.h is needed in C++ compilers
#ifdef __cplusplus
#include <unistd.h>
#endif

void main()
{

 int pfd[2]; // pfd - Pipe File Descriptor

 if(pipe(pfd) < 0)
    printf("\n Pipe error");

if(!fork())
{
   //child process
   char reni;
   printf("\n Enter any character to Exit:");
   scanf("%c", &reni);
   // writing to pipe
   write(pfd[1], &reni, 1);
   //child exit
  printf("\n Child Exiting..!");
  exit(0);
}
else
{
  // parent process
  char sam;
  // reading from pipe
  read(pfd[0], &sam, 1);
  printf("\n Parent Received %c from Child", sam);
  printf("\n Parent Exiting..!");
  exit(0);
}

}

No comments:

Post a Comment