Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!cs.utexas.edu!sdd.hp.com!decwrl!ucbvax!ucbarpa.Berkeley.EDU!edward From: edward@ucbarpa.Berkeley.EDU (Edward Wang) Newsgroups: comp.unix.questions Subject: Re: reliable reads from pipes Message-ID: <37970@ucbvax.BERKELEY.EDU> Date: 4 Aug 90 10:55:48 GMT References: <1990Aug3.233256.29659@NCoast.ORG> Sender: usenet@ucbvax.BERKELEY.EDU Reply-To: edward@ucbarpa.Berkeley.EDU.UUCP (Edward Wang) Organization: University of California, Berkeley Lines: 31 In article <1990Aug3.233256.29659@NCoast.ORG> atul@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.