However, another code sample, whilst not containing so much documentation, includes sample code for passing commands such as start, stop and restart. It also creates a PID file which can be handy for checking if the daemon is already running etc.
These samples both explain how to create the daemon. Are there any additional things that need to be considered? Is one sample better than the other, and why?
Sander Marechal's code sample is superior to the original, which was originally posted in 2004. I once contributed a daemonizer for Pyro, but would probably use Sander's code if I had to do it over.
There are many fiddly things to take care of when becoming a well-behaved daemon process:
prevent core dumps (many daemons run as root, and core dumps can contain sensitive information)
behave correctly inside a
set UID, GID, working directory, umask, and other process parameters appropriately for the use case
close all open file descriptors, with exclusions depending on the use case
behave correctly if started inside an already-detached context, such as
set up signal handlers for sensible daemon behaviour, but also with specific handlers determined by the use case
redirect the standard streams
stderr since a daemon process no longer has a controlling terminal
handle a PID file as a cooperative advisory lock, which is a whole can of worms in itself with many contradictory but valid ways to behave
allow proper cleanup when the process is terminated
actually become a daemon process without leading to zombies
Some of these are standard, as described in canonical Unix literature (Advanced Programming in the UNIX Environment, by the late W. Richard Stevens, Addison-Wesley, 1992). Others, such as stream redirection and PID file handling, are conventional behaviour most daemon users would expect but that are less standardised.