Can I get back stdout after redirection?

Matteo Gelosa matteo at ghost.unimi.it
Thu May 2 22:52:31 AEST 1991


pefv700 at perv.pe.utexas.edu writes:


> The subject says it all.

> From what I understand, with

> % cmd > file

> the typical shell will do something like (omitting error checking)

>     fd = fopen("file", "w");

<     fd = open("file", O_WRONLY)_;
	probably you wanted to write this...

>     close(1);
>     dup(fd);

> 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...

< #define STDOUT 1	/* I know 1 is standard output but it looks nicer */

<	fd = open("/dev/tty", O_RDWR);	/* open /dev/tty */
<	close(STDOUT);			/* close old redirection */
<	dup(fd);			/* re-redirect standard output to tty */

	Matteo.
----
Matteo Gelosa					Phone  : +39-2-7575242
Universita' Statale di Milano			Fax    : +39-2-76110556
Dipartimento di Scienze dell'Informazione	Telex  : 335199 - MIDSII
Via Moretto da Brescia, 9                       E-Mail : matteo at ghost.unimi.it
I-20133 Milano - Italy - `92 Europe



More information about the Comp.unix.programmer mailing list