reliable reads from pipes

Rick Jones rick at tetrauk.UUCP
Mon Aug 6 20:27:36 AEST 1990


In article <1990Aug3.233256.29659 at NCoast.ORG> atul at NCoast.ORG (Atul Parulekar) writes:
>The following program does not work all the time.  ...
>... 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];
>
>   [code for fork & child writing process]
>
>   n = read (fifo[0], line, 80);
>   line[n] = '\0';
>   printf ("Current directory is %s\n", line);
>}

In all implementations where I've used pipes, a read on the pipe returns as
many bytes as are in the pipe at the time of the read.  If the writing process
is not buffering its writes, then it may be scheduled out in the middle of a
line, and the read process will see the incomplete data.

You either need to loop on the read until you get EOF (i.e. when the writer has
closed the pipe), or better use fgets() which will only return on end-lines or
buffer full (so it does the looping for you).  If you have to pick up multiple
lines, then fgets() is definitely the way to do it.  Raw reads on pipes can be
as difficult as raw reads on serial lines.

Incidentally, you should always close the read end of the pipe in the writing
process, and the write end in the reading process immediately after the fork.
If you don't at least do the second of these, the read process will never see
EOF on the pipe when the writer exits, since it is keeping it open itself.

-- 
Rick Jones					You gotta stand for something
Tetra Ltd.  Maidenhead, Berks			Or you'll fall for anything
rick at tetrauk.uucp (...!ukc!tetrauk.uucp!rick)	     - John Cougar Mellencamp



More information about the Comp.unix.questions mailing list