Specify file descriptor number?

I realized that when opening a new file using open () it is not possible to control the file descriptor (integer) assigned by the OS. How then is it possible in the bash shell to assign a specific file descriptor using a command like

exec 5>&1 

(I guess I could find out by reading bash sources ...)

+4
source share
3 answers

I believe that you are correct that sometimes file descriptors may already be used. I got this from http://tldp.org/LDP/abs/html/io-redirection.html#FTN.AEN17716

"Using file descriptor 5 can cause problems. When Bash creates a child process, as with exec, the child inherits fd 5 (see" Chet Ramey Archived Email, " SUBJECT: RE: File descriptor 5 is open ). It is better to leave this specific fd only."

The solution to this issue is indicated in section 3.6 of paragraph 2 of the Bash manual.

Each redirection, which may be preceded by a file descriptor number, may be preceded by a word of the form {varname} . In this case, for each redirection operator except> & - and <& -, the shell will select a file descriptor greater than 10 and assign it {varname}. If> & - or <& - is preceded by the value {varname}, the value varname defines the file descriptor to close.

for instance

 #!/bin/bash exec {NEW_STDOUT}>&1 echo "Hello" >&$NEW_STDOUT exec {NEW_STDOUT}>&- 
+3
source

See dup2 Unix system call.

+3
source

In addition, file descriptors are assigned sequentially, so if you know that 0, 1, 2, ..., n are already open and none of them have been closed, the next one will be n + 1.

+1
source

All Articles