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?
In Unix, how do I redirect error messages to /dev/null? You can send output to /dev/null, by using command >/dev/null syntax. However, this will not work when command will use the standard error (FD # 2). So you need to modify >/dev/null as follows to redirect both output and errors to /dev/null.
Redirecting stdout and stderr to a file: The I/O streams can be redirected by putting the n> operator in use, where n is the file descriptor number. For redirecting stdout, we use “1>” and for stderr, “2>” is added as an operator.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With