Redirecting stdout, and then getting it back

Doug Gwyn gwyn at smoke.brl.mil
Fri Feb 15 09:16:59 AEST 1991


In article <1991Feb14.035930.20173 at berlioz.nsc.com> nelson at berlioz.nsc.com (Taed Nelson) writes:
>We have a "shell" program which executes programs from within it using the
>  system()/spawn() call.  We wanted to trap these errors, so we freopen()ed
>  stdout and stderr to files that we could parse/show to the user from within
>  the "shell".  This part works fine.

You were lucky.  The UNIX convention is that file descriptors 0, 1, and 2
are the standard I/O/error hooks.  While in a given stdio-using program
stdin, stdout, and stderr will start out assigned to those file
descriptors, there is no guarantee that the same file descriptors will
be in use for those stdio streams after the freopen()s.

To keep the original file descriptors from being lost by the freopen()s,
you can save the value of dup(fileno(stdio_stream_here)), then later use
dup2() to move them to the original values 0,1,2.



More information about the Comp.unix.questions mailing list