Path: utzoo!utgpu!news-server.csri.toronto.edu!clyde.concordia.ca!uunet!sco!md From: md@sco.COM (Michael Davidson) Newsgroups: comp.unix.wizards Subject: Re: How do I get EOF from a pipe I created? Summary: use popen() ... Keywords: pipe fork dup2 fdopen Message-ID: <7394@scolex.sco.COM> Date: 7 Aug 90 22:34:37 GMT References: <6366.26be9bd9@csv.viccol.edu.au> Sender: news@sco.COM Reply-To: md@sco.COM (Michael Davidson) Organization: The Santa Cruz Operation, Inc. Lines: 51 In article <6366.26be9bd9@csv.viccol.edu.au> timcc@csv.viccol.edu.au (Tim Cook) writes: >I am having a bit of fun writing a utility that parses the output of a >command that it exec's in a subprocess. What I am doing is basically >(minus error checking): > > int pipe_descriptors[2] ; > > pipe (pipe_descriptors) ; > if (fork ()) { > /* Subprocess */ > dup2 (pipe_descriptors[1], 1) ; /* Hey!! how about doing a close(pipe_descriptors[0]; here .... */ > execl ("/dir/command", "command", "arg", 0) ; > /*NOTREACHED*/ } > > /* Parent continues here */ > pipe_stream = fdopen (pipe_descriptors[0], "r") ; /* Hey!! how about doing a close(pipe_descriptors[1]; here .... */ > > while (! feof (pipe_stream)) { > fgets (buffer, sizeof (buffer) - 1, pipe_stream) ; /* now when the child closes the write side of the pipe (probably */ /* when it exits) you should see an EOF ... */ /* in the interests of "keeping your process table tidy" it would */ /* also be a really GOOD IDEA (TM) to do a wait() here */ > > /* Parsing of what is in "buffer"... */ > } > >Well, I get the output of "command" coming through on "pipe_stream", but >I don't get end-of-file. The fgets call just blocks when there is nothing >left in the pipe (and not because the last record output by "command" was >not terminated by a newline). Because there is still an open file which refers to the "write" side of the pipe - the fact that it is in your own process doesn't matter - you will never get an EOF from a pipe unless you set it up properly. In general, unless you *know* how to handle the necessary low level process and file manipulation necessary to set up pipes correctly *and* you have a good reason why the functionality provided by the library routine "popen()" is either unsuitable or inadequate you should use "popen()" and "pclose()"