简体   繁体   中英

specifying file descriptor number?

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

exec 5>&1

(I suppose I could find out by reading the bash sources...)

请参阅dup2 Unix系统调用。

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

"Using file descriptor 5 might cause problems. When Bash creates a child process, as with exec, the child inherits fd 5 (see Chet Ramey's archived e-mail, SUBJECT: RE: File descriptor 5 is held open ). Best leave this particular fd alone."

The solutiont to this is specified in section 3.6 paragraph 2 of the bash manual.

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

For example

#!/bin/bash

exec {NEW_STDOUT}>&1
echo "Hello" >&$NEW_STDOUT
exec {NEW_STDOUT}>&-

另外,文件描述符是按顺序分配的,因此,如果您知道0、1、2,...,n已打开,而没有一个已关闭,则下一个将为n + 1。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM