[comp.unix.wizards] Piping stdout in parent to stdin in child

throopw@dg_rtp.UUCP (11/22/86)

> mother@sunspot.UUCP (Leonard Sitongia)

> I want to connect up stdout IN THE PARENT to stdin in the child.  The
> approach I expect to work is:

Your example leaves too much out to tell if it would work or not (it
clearly wouldn't work as shown, as the fork()'s return value isn't
tested, so both parent and child process would do the same thing).
However, later on, you give a clue as to what you really want:

> What Im trying to accomplish is to take an existing program and pipe
> its stdout to a tee.  Why isnt this done on the shell level?  Because
> the program in question executes under an interactive data reduction
> system.  I dont want to half to dig into the code and change all the
> "printf"s to "fprintf"s.

So I coded up what you described:

        int close(), dup(), execl(), fork(), pipe(), printf();
        int main(){
            int p[2];
            pipe(p);
            if( fork() ){ /* parent, write on fd 1 */
                close(1); dup(p[1]); close(p[0]); close(p[1]);
            }
            else{ /* child, read on fd 0 */
                close(0); dup(p[0]); close(p[0]); close(p[1]);
                execl( "/usr/bin/tee", "tee", "foo", (char *)0 );
            }
            printf( "blah, blah, blah\n" );
            return(0);
        }

and it works quite well.  (True, on my machine the parent returns before
the tee has a chance to write the "blah, blah, blah" out to the screen,
but it DOES work.  Making the parent wait() after the printf would fix
that little problem, if it were really a problem.)

This program has two notable non-portabilities.  First, I assume that
"/usr/bin/tee" is where the tee program lives.  I suppose I could have
done an execlp to avoid this problem.  Second, I am assuming that the
replacements of the descriptors 0 and 1 will affect the library streams
stdin and stdout.  This is a fairly safe assumption, if it is done as
the first thing in main, though it is a *little* sleazy.  Most sleazy of
course, I've omitted all error checking.  Naturally, all those system
calls should be checked for proper completion, nyet?  But this
demonstrates the required structure most clearly, I think.

Howzat?  All clear?

--
The customer may not always be right, but he's always the customer.
                                --- David Gerrold
-- 
Wayne Throop      <the-known-world>!mcnc!rti-sel!dg_rtp!throopw