Search code examples
linuxunixdaemonfile-descriptor

UNIX daemon processes file descriptors


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!


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.