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
在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);
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?
我搞不清楚这三个人怎么知道他们正在重定向三个std*。特别是最后两个命令是相同的。有人能解释或指出我的正确方向吗?
2 个解决方案
#1
13
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,并且没有其他线程可能正在分配新的文件描述符。在这种情况下,由于需要始终分配最低可用的文件描述符编号,所以这三个调用打开将产生文件描述符0,1和2,除非它们失败。
#2
4
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.
这是因为文件描述符0、1和2分别是输入、输出和错误,并且打开将获取可用的第一个文件描述符。注意,只有当文件描述符0、1和2没有被使用时,这才会起作用。
And you should be careful about the terms used, stdin
, stdout
and stderr
are actually file handles (FILE*
) rather than file descriptors, although there is a correlation between those and the file descriptors.
您应该注意使用的术语,stdin、stdout和stderr实际上是文件句柄(文件*),而不是文件描述符,尽管它们和文件描述符之间存在关联。
#1
13
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,并且没有其他线程可能正在分配新的文件描述符。在这种情况下,由于需要始终分配最低可用的文件描述符编号,所以这三个调用打开将产生文件描述符0,1和2,除非它们失败。
#2
4
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.
这是因为文件描述符0、1和2分别是输入、输出和错误,并且打开将获取可用的第一个文件描述符。注意,只有当文件描述符0、1和2没有被使用时,这才会起作用。
And you should be careful about the terms used, stdin
, stdout
and stderr
are actually file handles (FILE*
) rather than file descriptors, although there is a correlation between those and the file descriptors.
您应该注意使用的术语,stdin、stdout和stderr实际上是文件句柄(文件*),而不是文件描述符,尽管它们和文件描述符之间存在关联。