Featured Post

Friday, June 24, 2016

Inter process communication using named pipe(FIFO)



   The drawback of normal pipe is only the processes related to process that created the pipe may communicate among them. A named pipe is one which is stored in the disk and two unrelated process can communicate each other.

syntax to create name pipe:
             mknod("mypipe",S_IFIFO|0644,0);/*Syntax to create named pipe in UNIX program*/
  
         from command prompt we can create named file 

         mknod mypipe p

Inter process communication using named pipes

(execute two programs simultaneously in two command prompts. Producer will get struck until a consumer is ready to read and consumer will get struck until a producer is ready to place data.)


//producer.c
#include<stdio.h>
#include<sys/stat.h>
#include<string.h>
#include<unistd.h>
#include<fcntl.h>
#include<errno.h>
#include<stdlib.h>
#define FIFO_NAME "XYZ"
void main()
{
  int num,fd;
   char s[300];
   mknod(FIFO_NAME,S_IFIFO|0666,0);
   printf("waiting for readers\n");
   fd=open(FIFO_NAME,O_WRONLY);
   printf("got a reader type some stuff");
   while(gets(s),!feof(stdin))
   {
     if((num=write(fd,s,strlen(s)))==-1)
       perror("write");
     else
     printf("speak:wrote %d bytes\n", num);
   }
}

OUTPUT:
  waiting for readers
  got a reader type some stuff
hi hello
  speak:wrote 8 bytes

//Consumer.c
#include<stdio.h>
#include<sys/stat.h>
#include<unistd.h>
#include<sys/types.h>
#include<fcntl.h>
#include<errno.h>
#define FIFO_NAME "XYZ"
void main()
{
  char s[300];
    int num,fd;
  mknod(FIFO_NAME,S_IFIFO|0666,0);
    printf("waiting for writers\n");
    fd=open(FIFO_NAME,O_RDONLY);
    printf("got a writer\n");
    do
     {
       if((num=read(fd,s,300))==-1)
             perror("read");
        else
         {
             s[num]='\0';
             printf("read %s ",s);
         }
     }while(num>0);
}

OUTPUT:
    waiting for writers
    got a writer 
    read hi hello



IPC using named pipe, pipe, producer consumer problem, shared memory, SIGPIPE , semaphores, inter process communication



No comments:

Post a Comment