#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>  
#include <errno.h>
#define BUFSIZE 256
int main (int argc, char *argv[])
{
   mode_t fifo_mode = S_IRUSR | S_IWUSR;
   int fd;
   int bytes_read;
   char buf[BUFSIZE];

   if (argc != 2) {
      fprintf(stderr, "Usage: %s pipename\n", argv[0]);
      return 1;
   }
                          /* create a named pipe with r/w for user */
   if ((mkfifo(argv[1], fifo_mode) == -1) && (errno != EEXIST)) {
      fprintf(stderr, "Could not create a named pipe: %s\n", argv[1]);
      return 1;
   }
 
   fprintf(stderr, "Process %ld about to open FIFO %s\n",
                       (long)getpid(), argv[1]);
   if ((fd = open(argv[1], O_RDONLY)) == -1) {
         perror("process cannot open FIFO for read");
         return 1;
   } 
   fprintf(stderr, "FIFO now open for read.\n");
   while ((bytes_read = read(fd, buf, BUFSIZE)) != 0) {
      if (bytes_read <  0) {
            perror("read from FIFO failed\n");
            return 1;
      } 
      if (write(STDOUT_FILENO,buf,bytes_read) != bytes_read) {
         fprintf(stderr,"error writing to standard output\n");
         return 1;
      }
   }
   fprintf(stderr,"FIFO was closed\n");
   return 0;
}

