daemonize-doublefork-0.1.0: Start background daemons by double-forking

System.Posix.Daemon

Contents

Description

This module provides startDaemon and stopDaemon to facilitate the creation of daemon programs.

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 nginx and emacs --daemon.

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.

Synopsis

Daemon control

startDaemonSource

Arguments

:: FilePath

PIDFILE

-> IO ()

HANDLER

-> IO ()

PROGRAM

-> IO () 

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 started with SIGHUP masked; HANDLER is invoked on SIGHUP.

See: http://www.enderunix.org/docs/eng/daemon.php

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

stopDaemonSource

Arguments

:: FilePath

PIDFILE

-> IO (Maybe ProcessID) 

Stop the daemon identified by PIDFILE by sending it SIGHUP. If the process was daemonized with startDaemon, the handler specified there will be invoked first. Return the pid of the process that was killed; if PIDFILE does not exist, return Nothing.

Utilities

becomeGroupUserSource

Arguments

:: String

GROUP

-> String

USER

-> IO () 

Make the current process belong to USER and GROUP.