开发者

Redirecting STDIN, STDOUT, STDERR to /dev/null in C

开发者 https://www.devze.com 2023-01-26 09:27 出处:网络
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

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?


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.


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 and stderr are actually file handles (FILE*) rather than file descriptors, although there is a correlation between those and the file descriptors.

0

精彩评论

暂无评论...
验证码 换一张
取 消