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