Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 785
Paul Avatar asked Nov 24 '10 03:11

Paul


People also ask

How do I send stderr to Dev Null?

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.

How do you redirect stdin stdout and stderr to a file?

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.


2 Answers

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.

like image 60
R.. GitHub STOP HELPING ICE Avatar answered Oct 04 '22 13:10

R.. GitHub STOP HELPING ICE


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.

like image 40
paxdiablo Avatar answered Oct 04 '22 15:10

paxdiablo