sh:如何避免破坏编号的文件描述符?
当我有时,
exec 3>>file # file descriptor 3 now points to file
[ $dryrun ] && exec 3>&1 # or possibly to stdout
echo "running">&3
exec 3>&- # and is now closed
我担心文件描述符 3 可能指向相关函数之外的内容。我该如何处理这个问题?
- 是否有内置的
next_available_fd
? - 有没有办法将 fd3 复制到变量,然后在函数完成后将其复制回来?
- 在这种情况下我应该担心线程和并发写入 fd3 吗?
- 我在 sh,但也许 bash/ksh/zsh 有这个问题的答案?
When I have
exec 3>>file # file descriptor 3 now points to file
[ $dryrun ] && exec 3>&1 # or possibly to stdout
echo "running">&3
exec 3>&- # and is now closed
I'm worried about what file descriptor 3 may have pointed to outside of the function in question. How can I handle this?
- Is there a builtin
next_available_fd
? - Is there a way to duplicate fd3 to a variable, then dup it back once the function is done?
- and should I worry about threading and concurrent writes to fd3 in this case?
- I'm in sh, but maybe bash/ksh/zsh has an answer to this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以(使用 bash,我没有尝试使用其他 shell)执行以下操作,而不是使用 exec 在函数内重定向文件描述符:
在此设置中,“运行”将转到文件或原始标准输出,具体取决于$dryrun 和 more_commands 将具有 fd 3,就像调用 foo 之前一样。
Instead of using exec to redirect the file descriptor within the function, you can (with bash, I haven't tried with other shells) do:
In this setup, "running" will go to either the file or to the original stdout depending on $dryrun, and more_commands will have fd 3 as it was before foo was called.
我不知道像
next_available_fd
这样简单的事情,但是要获得您想要的功能(临时重定向文件描述符而不影响函数外部)可以在 bash 中按以下方式完成(我不知道不知道 sh):生成的
file1
:和
file3
:这表明重定向仅限于每种情况下的函数调用。
I don't know about anything as simple as
next_available_fd
, but to get the functionality that you want (temporarily redirecting a file descriptor without affecting it outside the function) can be accomplished as follows in bash (I don't know about sh):The resulting
file1
:And
file3
:Which demonstrates that the redirection is restricted to the function call in each case.
如果您的系统使用
/proc
文件系统,请查看/proc/$$/fd
看看正在使用什么。If your system uses the
/proc
filesystem, look inside/proc/$$/fd
to see what's in use.