How do I get EOF from a pipe I created?

Michael Davidson md at sco.COM
Wed Aug 8 08:34:37 AEST 1990


In article <6366.26be9bd9 at csv.viccol.edu.au> timcc at 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()"



More information about the Comp.unix.wizards mailing list