Newsgroups: comp.unix.questions
Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!usenet.ins.cwru.edu!ncoast!atul
From: atul@NCoast.ORG (Atul Parulekar)
Subject: reliable reads from pipes
Organization: North Coast Public Access *NIX, Cleveland, OH
Date: Fri, 3 Aug 90 23:32:56 GMT
Message-ID: <1990Aug3.233256.29659@NCoast.ORG>

The following program does not work all the time.  Most of the times it works
(gives the correct directory (/users/prog/test) followed by a carriage return)
but sometimes it does not print out the full directory name (prints (/) not
followed by a carriage return.)  I am not sure whether it is not reading from
the pipe completely or not printing out the complete message.  Any ideas and/or
suggestions for improvements?  I am trying to write a program which calls
another program passing it some parameters and getting back some output.

#include <stdio.h>

main ()
{
   int fifo[2],proc,n;
   char line[81];

   pipe (fifo);
   if ((proc=fork ()) = -1) {
      fprintf (stderr,"Cannot fork\n");
      exit (1);
   }
   if (proc == 0) {
      close (1);	/*close std o/p and dup write end of pipe to it */
      dup (fifo[1]);

      execlp ("pwd", "pwd", (char *) 0);

      fprintf (stderr, "Cannot exec pwd\n");
      exit (2);
   }

   n = read (fifo[0], line, 80);
   line[n] = '\0';
   printf ("Current directory is %s\n", line);
}

