gpt4 book ai didi

c - 指定文件描述符编号?

转载 作者:IT王子 更新时间:2023-10-29 01:07:06 28 4
gpt4 key购买 nike

我的理解是,当使用 open() 打开一个新文件时,无法控制操作系统分配的文件描述符(整数)。那么如何在 bash shell 中使用像

这样的命令分配特定的文件描述符呢?
exec 5>&1

(我想我可以通过阅读 bash 源代码找到答案...)

最佳答案

我相信您是对的,有时文件描述符可能已经在使用中。我从 http://tldp.org/LDP/abs/html/io-redirection.html#FTN.AEN17716 得到这个

“使用文件描述符 5 可能会导致问题。当 Bash 创建子进程时,与 exec 一样,子进程继承 fd 5(请参阅 Chet Ramey 的存档电子邮件,SUBJECT: RE: File descriptor 5 is held open)。最好不要管这个特定的 fd。”

bash 手册第 3.6 节第 2 段中指定了解决方案。

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.

例如

#!/bin/bash

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

关于c - 指定文件描述符编号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3425021/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com