Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!uunet!mcsun!ukc!pyrltd!tetrauk!rick From: rick@tetrauk.UUCP (Rick Jones) Newsgroups: comp.unix.questions Subject: Re: reliable reads from pipes Message-ID: <712@tetrauk.UUCP> Date: 6 Aug 90 10:27:36 GMT References: <1990Aug3.233256.29659@NCoast.ORG> Reply-To: rick@tetrauk.UUCP (Rick Jones) Organization: Tetra Ltd., Maidenhead, UK Lines: 39 In article <1990Aug3.233256.29659@NCoast.ORG> atul@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 > >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@tetrauk.uucp (...!ukc!tetrauk.uucp!rick) - John Cougar Mellencamp