file descriptor redirection, exec

–Annotations on http://tldp.org/LDP/abs/html/ioredirintro.html

bash$ lsof -a -p $$ -d0,1,2
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
bash 363 bozo 0u CHR 136,1 3 /dev/pts/1
bash 363 bozo 1u CHR 136,1 3 /dev/pts/1
bash 363 bozo 2u CHR 136,1 3 /dev/pts/1

bash$ exec 2> /dev/null
bash$ lsof -a -p $$ -d0,1,2
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
bash 371 bozo 0u CHR 136,1 3 /dev/pts/1
bash 371 bozo 1u CHR 136,1 3 /dev/pts/1
bash 371 bozo 2w CHR 1,3 120 /dev/null <—

http://tldp.org/LDP/abs/html/x17601.html#USINGEXECREF shows —

exec 6>&1 # Link file descriptor #6 with stdout.
# I think this creates a new file descriptor FD#6 as alias of FD#1. FD#6 is probably a **pointer** to the in-memory object FD#1. The object IS the original file descriptor.

exec > $LOGFILE 2>&1 # stdout replaced with file “logfile.txt”.
# the object is not discarded. FD#6 still points to it, but the current process no longer uses that object.

#### this is a useful thing to put into your script, if someone calls your script.

# now the current process will use the original “object” from now on.
exec 1>&6 6>&- # Restore stdout and close file descriptor #6.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s