Redirection of stderr

Jonathan I. Kamens jik at athena.mit.edu
Mon Mar 18 14:51:01 AEST 1991


In article <TB.91Mar15072648 at sequent.sequent.com>, tb at sequent.sequent.com (Tony Booker) writes:
|> In article <1991Mar14.225058.13507 at athena.mit.edu> jik at athena.mit.edu (Jonathan I. Kamens) writes:
|>    However, if you do things this way, I can't see any way to put the
|>    original stderr back in place -- there is no "fdreopen".  That's
|>    unfortunate.
|> 
|> I beleive the return value of freopen() is the original file for you
|> to salt away as necessary.

>From freopen(3):

     Freopen substitutes the named file in place of the open
     stream.  It returns the original value of stream.  The ori-
     ginal stream is closed.

In other words, yes, it returns the original stream, but it's closed and
replaced by the new file, so you can't do anything useful with it.  To verify
this, compile and run the following program.  If what you say works, then the
second fprintf should cause output to go to the tty; if not, the second
fprintf should appear in the testfile.  On my system, it does.

#include <stdio.h>

#define TESTFILE "/tmp/freopen-testfile"

main()
{
     FILE *old;

     old = freopen(TESTFILE, "w", stdout);

     fprintf(stdout, "This is being written to stdout, now %s.\n",
	     TESTFILE);
     fprintf(old, "This is being written to the old stdout.\n");

     fclose(stdout);
     fclose(old);
     
     exit(0);
}

-- 
Jonathan Kamens			              USnail:
MIT Project Athena				11 Ashford Terrace
jik at Athena.MIT.EDU				Allston, MA  02134
Office: 617-253-8085			      Home: 617-782-0710

P.S. It's usually a good idea to actually try suggestions like this out before
posting them to the net.  Yes, I know, I'm not one to talk, considering that I
posted about assigning to stderr when that won't work on most systems anyway. 
But I thought I'd point it out anyway. :-)



More information about the Comp.unix.questions mailing list