Question

I read in different sources that a common thing to do for a process that would become a daemon is to redirect STDIN, STDOUT, STDERR to /dev/null in order to prevent the daemon from spamming the console, which makes perfect sense.

I was curious why redirect them to null, when you could just close them. Any reason for this?

Thanks!

Was it helpful?

Solution

If you just close them:

  • new file descriptors gets the lowest descriptor number possible. If fd 0/1/2 is closed, a new socket you create, or file you open would be assigned to those fd's. Which means you risk dumping stuff that should go to stdout onto that socket or file.

  • accidental printfs etc. that prints to stdout, or for some reason try to read from stdin would fail, and possibly your program would exit if it tries to operate on a file descriptor that does not exist.

OTHER TIPS

After close,

  • Calling open(2) creates another file descriptor that could possiblly replacing STDIN, STDOUT, STDERR. (intentionally or accidently); Some programs use dup2(2) to get similar effect, instead of using close + open.

  • Without open(2), reading from/writing to STDIN, STDOUT, STDERR could cause error. Depending on how the program react to such error, the program will exit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top