1

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!

Alex
  • 635
  • 6
  • 15

2 Answers2

3

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.

nos
  • 223,662
  • 58
  • 417
  • 506
1

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.

falsetru
  • 357,413
  • 63
  • 732
  • 636