7

I have seen in SO how to redirect STDIN, STDOUT, STDERR to /dev/null in C . This is done during startup of a daemon. But, why is this necessary for a proper startup of a unix/linux daemon?

Bonus Question :

What happens if STDOUT is closed and file descriptor is used without re-opening ?

Community
  • 1
  • 1
smRaj
  • 1,246
  • 1
  • 9
  • 13
  • I suggest checking this very suitable and good answer -> http://stackoverflow.com/a/4869937/1983854 – fedorqui Oct 21 '13 at 11:04

2 Answers2

8

stdin, stdout and stderr are closed so that the daemon can detach successfully from the tty it was started from and also so that the daemon (or its child processes) won't write to the tty when its running.

If you attempt to read/write from a closed file descriptor, the operation will fail and errno will be set to EBADF ("fildes is not a valid file or socket descriptor open for reading"). Other than that, nothing untoward will happen.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • 2
    There's another reason you'd want to redirect to /dev/null, namely that creating new file descriptors (e.g. opening a file, creating a new socket, pipe, etc.) will use the lowest available file descriptor number. So if a daemon creates a socket that happens to become stdout/err, you don't want lingering debug printf's/asserts, perror() calls or similar to end up on the socket - better direct them to /dev/null. – nos Oct 21 '13 at 11:18
1

TL;DR

You shouldn't. It is not necessary for a proper startup of a unix/linux daemon. Always write your log messages to stderr.

Bonus

errno is set to EBADF if a closed file descriptor is used, and the operation will fail.

Summary

Don't daemonize your program inside itself. Use a daemon manager to daemonize it. (Remember? Do one thing and do it right.)

Whatever program you write, always log to stderr. Doing so has the following advantages, and I quote Jonathan de Boyne Pollard:

  • The logging output from your dæmon will as a consequence automatically be entirely separate from the logging output of other dæmons.
  • You won't need any extra files in the chroot() jail at all.
  • Log data will not be lost and will be recorded in the same order that they were generated.
  • Other programs/people will not be able to insert spoof messages into the output.

Redirecting stderr to /dev/null will make it a lot harder for sysadmin to aggregate your log into their systems. You may enrage them by doing the following, I quote Chris Jester Yang:

  • Insist on using syslog, and don't provide any options to log to standard error or standard output.
  • Just to be sure, explicitly close file descriptors 1 and 2, or redirect them to /dev/null.

Reference

Yufan Lou
  • 132
  • 9