linux - 重定向到/dev/null 和简单地关闭流之间的有效区别是什么

标签 linux bash io-redirection

背景:
我想在受限 bash 的修改环境中测试一些 bash 脚本。在受限的 bash 中,我不允许将流重定向到文件,例如2>/dev/null
我通过简单地使用例如关闭流找到了解决方法2>&-

虽然在这里和那里尝试,但我发现 2>/dev/null2>&-
之间没有有效区别 STDERR 输出被吞没了,没有出现。

$ bash -c 'ls FOO'
ls: cannot access FOO: No such file or directory
$ bash -c 'ls FOO 2>/dev/null'
$ bash -rc 'ls FOO 2>/dev/null'
bash: /dev/null: restricted: cannot redirect output
$ bash -rc 'ls FOO 2>&-'
$ bash -rc 'ls FOO 2>&- ; ls BAR'
ls: cannot access BAR: No such file or directory

我想 bash 内部的处理是不同的,但这对我来说并不重要。对我来说重要的是,一般关闭而不是重定向到/dev/null 会导致任何问题吗?

最佳答案

这取决于程序在做什么。

如果你close(2)一个file descriptor , 然后是 future open(2)将重新使用相同的文件描述符。还有, future write(2) (没有任何 open)将失败并返回 EINVAL

大多数程序都懒得去检查,例如printf(3)成功了(理论上,他们应该)。

如果你成功重定向到/dev/null write(2)总是成功的。阅读null(4) .

我建议尽可能重定向到 /dev/null

关于linux - 重定向到/dev/null 和简单地关闭流之间的有效区别是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22353300/

相关文章:

c - 修复线程以在某些内核上执行

linux - 1and1 和简单的 htaccess 重定向失败

windows - 如何在 Windows 中更改 Git 终端的标题?

bash - bash 中嵌套循环的奇怪行为

eclipse - 在 Eclipse 中运行程序时将标准输出与标准错误分开

c - 为什么将标准输出重定向到文件时,C 程序的输出顺序不同?

linux - awk 命令 : how to tell it to distinguish between space and tab delimiter

linux - UDEV - 在插入的 USB 闪存驱动器上运行程序

linux - 为什么我的 bash 脚本不能正确运行?

python - 使用 FIFO 在没有 stdin/stdout 的情况下运行 pdb