Can I get back stdout after redirection?

Michael Meissner meissner at osf.org
Sat May 4 06:08:57 AEST 1991


In article <1991May02.125231.20488 at ghost.unimi.it>
matteo at ghost.unimi.it (Matteo Gelosa) writes:

| > Since the shell has already closed stdout's file descriptor, is it not
| > possible to reopen it?  (Also, how did stdout get opened in the first
| > place?  The shell inherited it from its parent, didn't it?)
| 
| 	There is a special file named "/dev/tty", that always refers
| 	to your current tty. Simply you have to reopen it if you want
| 	to send your output back to your tty.
| 	A lot of programs that have to communicate only with a tty
| 	device do it to avoid redirection.
| 	Try with this...

However, /dev/tty is not the same thing as stdout (though for many
users it winds up at the same location).  If you need to restore your
original stdout after redirection, the only way is not to close your
last handle on it.  I would recomend:

	orig_stdout = dup (fileno (stdout));
	if (orig_stdout < 0)
	  {
	    perror ("dup");
	    abort ();
	  }

	if (freopen ("newfile", "a", stdout) != stdout)
	  {
	    perror ("newfile");
	    abort ();
	  }

	/* whatever */

	fclose (stdout);
	if (fdopen (orig_stdout, "w") == 0)
	  {
	    perror ("fdopen");
	    abort ();
	  }

for the adventuresome, you can play games with dup behind stdio's
back, but it's not something I recomend.....

--
Michael Meissner	email: meissner at osf.org		phone: 617-621-8861
Open Software Foundation, 11 Cambridge Center, Cambridge, MA, 02142

Considering the flames and intolerance, shouldn't USENET be spelled ABUSENET?



More information about the Comp.unix.programmer mailing list