在 C 中将 STDIN、STDOUT、STDERR 重定向到 /dev/null
在 Stevens 的《UNIX 网络编程》中,他提到了重定向 stdin、stdout 和 stderr,这在设置守护程序时是需要的。他用下面的 C 代码来做到这一点,
/* redirect stdin, stdout, and stderr to /dev/null */
open("/dev/null", O_RDONLY);
open("/dev/null", O_RDWR);
open("/dev/null", O_RDWR);
我很困惑这三个“知道”它们正在重定向三个 std*。特别是因为最后两个命令是相同的。有人可以解释或指出我正确的方向吗?
In Stevens' UNIX Network Programming, he mentions redirecting stdin, stdout and stderr, which is needed when setting up a daemon. He does it with the following C code
/* redirect stdin, stdout, and stderr to /dev/null */
open("/dev/null", O_RDONLY);
open("/dev/null", O_RDWR);
open("/dev/null", O_RDWR);
I'm confused how these three 'know' they are redirecting the three std*. Especially since the last two commands are the same. Could someone explain or point me in the right direction?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据推测,当此代码执行时,文件描述符 0、1 和 2 已经关闭,并且没有其他线程可能正在分配新的文件描述符。在这种情况下,由于
open
需要始终分配最低的可用文件描述符编号,因此这三个对 open 的调用将产生文件描述符 0、1 和 2,除非它们失败。Presumably file descriptors 0, 1, and 2 have already been closed when this code executes, and there are no other threads which might be allocating new file descriptors. In this case, since
open
is required to always allocate the lowest available file descriptor number, these three calls to open will yield file descriptors 0, 1, and 2, unless they fail.这是因为文件描述符 0、1 和 2 分别是输入、输出和错误,并且 open 将获取第一个可用的文件描述符。请注意,这仅在文件描述符 0、1 和 2 尚未使用时才有效。
你应该小心使用的术语,
stdin
,stdout
和stderr
实际上是文件句柄(FILE*
)而不是文件描述符,尽管它们和文件描述符之间存在相关性。It's because file descriptors 0, 1 and 2 are input, output and error respectively, and open will grab the first file descriptor available. Note that this will only work if file descriptors 0, 1 and 2 are not already being used.
And you should be careful about the terms used,
stdin
,stdout
andstderr
are actually file handles (FILE*
) rather than file descriptors, although there is a correlation between those and the file descriptors.