Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reopen STDOUT and STDERR after closing them?

Tags:

bash

In bash consider I did this stupid thing:

$ exec 1>&-
$ exec 2>&-

I am sure I have not yet lost the game (oops actually I lost The Game) and I can reconnect to stdout. The think is I don't know how.

First thing I tried is create a fifo and using another shell to monitor stdout of the first shell. It did not work, I don't know why:

tty1

$ mkfifo stdout
$ exec 1>stdout
$ echo "Hello stdout"

tty2

$ tail -f stdout
$ # nothing here

How can I reconnect my closed STDOUT and STDERR after all?

I know that a solution would be to save STDOUT before playing with it:

$ exec 3>&1
$ exec 1>&-
$ echo "Nothing will see this"
$ exec 1<&3 # Restoring stdout
like image 499
nowox Avatar asked Jun 21 '15 19:06

nowox


People also ask

Can stdout be closed?

Programs are also free to explicitly close stdout or stderr ; if they do not do so, these streams will be closed upon program termination. Closing any output stream requires flushing any data that has not yet been written to the stream.

What is the difference between stdout and stderr in a running process?

stdout: Stands for standard output. The text output of a command is stored in the stdout stream. stderr: Stands for standard error. Whenever a command faces an error, the error message is stored in this stream.

What is stdout and stderr?

stdout − It stands for standard output, and is used to text output of any command you type in the terminal, and then that output is stored in the stdout stream. stderr − It stands for standard error. It is invoked whenever a command faces an error, then that error message gets stored in this data stream.

What is Stdin_fileno?

STDIN_FILENO is the default standard input file descriptor number which is 0 . It is essentially a defined directive for general use.


1 Answers

I am running this on an Ubuntu machine, so I am not sure if it'll work for you, but this is what I did:

$ exec 1>&0
$ exec 2>&0

Suddenly, I had STDOUT and STDERR reconnected. Magic!

Explanation: Running the following commands, we get the following output:

$ ls -l /dev/stdout
lrwxrwxrwx 1 root root 15 Jun 11 23:39 /dev/stdout -> /proc/self/fd/1

$ ls -l /proc/self/fd/1
lrwx------ 1 jay jay 64 Jun 22 01:34 /proc/self/fd/1 -> /dev/pts/10

$ ls -l /proc/self/fd/
total 0
lrwx------ 1 jay jay 64 Jun 22 01:35 0 -> /dev/pts/10
lrwx------ 1 jay jay 64 Jun 22 01:35 1 -> /dev/pts/10
lrwx------ 1 jay jay 64 Jun 22 01:35 2 -> /dev/pts/10
lr-x------ 1 jay jay 64 Jun 22 01:35 3 -> /proc/12224/fd

Since all three fd's point to the same thing, we can return them back to normal just by pointing to /dev/pts/10 which the exec 1>&0 and exec 2>&0 do

like image 186
Jay Bosamiya Avatar answered Oct 13 '22 09:10

Jay Bosamiya