Do you write Unix daemons? Do you feel tired of life, and wish daily for hordes of sysadmins to put you out of your misery? Fear not: just follow these tips!

Initialisation

  1. Insist on backgrounding, and don't provide any options to run in the foreground.
  2. If foreground mode is supported, make it only available as part of a debug option that will flood the logs and/or make the program run ten times slower.
  3. Make sure to close all open file descriptors. Just to be sure, close all the way up to the maximum file descriptor value allowed by the system, in order to stop fghack working.
  4. While you're at it, double-check that file descriptor 0 is closed as well, just to stop the the fghack workaround working.
  5. Close the above-mentioned file descriptors using direct system calls, so that they cannot be masked by overriding close in an LD_PRELOADed library.

Logging

  1. Insist on using syslog, and don't provide any options to log to standard error or standard output.
  2. Just to be sure, explicitly close file descriptors 1 and 2, or redirect them to /dev/null.
  3. If logging to file is supported, make it work only on regular files. Just to be sure that the output is a regular file, seek to the end of the file before writing instead of opening in append mode.
  4. Be sure to close the logging file after every line. You wouldn't want to write to a rotated-out log file, would you?
  5. Always write local-time timestamps in log lines, and don't give an option to turn this off. You wouldn't want users to miss when something happened, would you?
  6. Instead of calling syslog, connect to /dev/log (or write to UDP port 514) directly, so log messages cannot be redirected elsewhere.
  7. Perform the above-mentioned connections and/or writes using direct system calls.

Rationale

Here are some (serious) reasons why the above are so frustrating.

Also, Jonathan de Boyne Pollard expands on some of my points in greater detail in Mistakes to avoid when designing Unix dæmon programs.