reliable reads from pipes
Edward Wang
edward at ucbarpa.Berkeley.EDU
Sat Aug 4 20:55:48 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.
>. . .
> int fifo[2],proc,n;
> char line[81];
>
> pipe (fifo);
> [fork an exec of pwd]
> n = read (fifo[0], line, 80);
> line[n] = 0;
> . . .
This may be of general interest.
The problem is that pwd may be writing less than the who path at a time.
The solution is to keep reading until end of file (n = 0) or error (n < 0).
There's no danger of looping because some progress is always made.
In the best Unix style,
char *p, *q;
for (q = (p = line) + sizeof line - 1;
p < q && (n = read(fifo[0], p, q - p)) > 0;
p += n)
;
*p = 0;
/* if desired, check for overflow (p == q) or read error (n < 0) */
Something like this is also a good idea when writing,
because signals may cause partial writes to return.
Standard IO is well known for not doing this correctly.
More information about the Comp.unix.questions
mailing list