The problem is as follows: the user starts a program in their
terminal, but he wants the program to relinquish control of the
terminal immediately, and furthermore, the program (or part of it)
should keep running even after said terminal is closed. Examples
of programs that behave like this are
The correct solution is to double-fork a process. This ensures that the child process is completed separated from the terminal it was started on.
Double-fork to create a well behaved daemon. If PIDFILE is
given, check/set pidfile; if we cannot obtain a lock on the file,
another process is already using it, so fail. The program is
SIGHUP masked; HANDLER is invoked on
Note: All unnecessary fds should be close before calling this.
HANDLER is meant to allow the daemon to shutdown cleanly. It could simply be:
handler = return ()
or something more elaborate like the following, which allows one to perform some actions before re-raising the signal and killing the daemon:
handler = do putStrLn Stopping daemon... raiseSignal sigTERM