#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;
   char buf[BUFSIZE];
   int bytes_read;

   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_WRONLY))== -1) {
      perror("Process cannot open FIFO for write");
      return 1;
   } 
   fprintf(stderr,"FIFO now open for write.\n");
   while ((bytes_read = read(STDIN_FILENO,buf,BUFSIZE)) != 0) {
      if (bytes_read < 0) {
         fprintf(stderr,"Error reading from standard input\n");
         return 1;
      } 
      if (write(fd, buf, bytes_read) != bytes_read) {
         fprintf(stderr, "Writing to pipe failed\n");
         return 1;
      } 
        
   }
   fprintf(stderr,"Standard input was closed\n");
   return 0;
}

