Could an existing fd always be duplicated both as input and output?

*爱你&永不变心* 提交于 2019-12-06 08:23:59

问题


In bash, once a fd is in use (either as input or output):

exec 7>AFile

It seems that that fd number could be duplicated, both as input or output:

true <&7; echo $?
true >&7; echo $?

The tests could be repeated for a variable as:

fd=7
rco="$(true >&${fd} 2>/dev/null; echo $?)"
rci="$(true <&${fd} 2>/dev/null; echo $?)"

And both exit values joined in one word as:

[[ "$rco$rci" = "11" ]] && echo "The fd number $fd is free"

The question is:

Under which conditions will the exit value of "$rco$rci" be different of 11 for a "free" fd number.

In other words: could it be 10 or 01 sometimes?

Could it be either in other shells?


回答1:


Never. Under the hood, the redirections will attempt to dup an existing or free filedescriptor and then the shell should proceed to run true if the preliminary redirections succeeded.

duping from an unopen descriptor should always fail, which effectively means one attempted redirection in either direction should be enough to test whether a filedescriptor is open or not.

( Conversely,duping from an open descriptor should almost always succeed. It fails when you've run out of your per-process filedescriptor limit which is usually 1024-4096, and you could theoretically get a permission fail if the shell tried to reset the open flags, but dash, bash, and zsh don't appear to try to do this. I only get IO errors when I actually try to write to a duped readonly filedescriptor, not during the redirection. )



来源:https://stackoverflow.com/questions/41641202/could-an-existing-fd-always-be-duplicated-both-as-input-and-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!