是否可以将现有的fd始终复制为输入和输出? [英] Could an existing fd always be duplicated both as input and output?

查看:88
本文介绍了是否可以将现有的fd始终复制为输入和输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在bash中,一旦使用fd(作为输入或输出):

exec 7>AFile

似乎fd号可以重复,无论是输入还是输出:

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

对于以下变量,可以重复测试:

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

两个出口值都用一个词表示为:

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

问题是:

对于免费" fd编号,在哪种情况下"$rco$rci"的退出值将不同于11.

换句话说:有时候是10还是01?

可以在其他外壳中使用吗?

解决方案

从不. 在后台,重定向将尝试 dup 现有或免费的文件描述符,然后如果初步重定向成功,则shell应该继续运行true.

从未打开的描述符中进行

dup总是应该失败,这实际上意味着在任一方向上尝试进行重定向都应该足以测试文件描述符是否处于打开状态.

(相反,从打开的描述符进行的dup几乎应该总是成功.当您用完了通常每个进程的文件描述符限制(通常为1024-4096)时,它就会失败,并且从理论上讲,如果shell尝试重置打开标志,但破折号,bash和zsh似乎没有尝试这样做.我仅在实际尝试写入复制的只读文件描述符时才收到IO错误,而不是在重定向过程中.) /p>

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?

解决方案

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. )

这篇关于是否可以将现有的fd始终复制为输入和输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆