Saturday, February 21, 2009

hdaemonize - for enunuchs demons in haskell

Writing little programs that stay live and do work, should not be hard, right? Well, on the UNIX platform it is not quite so! Just search the net for "LINUX Daemon Writing HOWTO.." hdaemonize collects all the cruft daemons do into a library, so that you can do this:

import Control.Concurrent
import System.Posix.Daemonize

main = daemonize $ \log ->
       do flag <- newEmptyMVar 
          let stop   = do log "STOPPING"
                          putMVar flag ()
          let loop i = do threadDelay $ 10^6
                          writeFile "/tmp/counter" $ show i
                          loop $ i + 1
          let start  = do log "STARTING UP"
                          forkIO $ loop 0
                          takeMVar flag
          let reload = log "RELOAD SIGNAL CAUGHT"
          return $ Program start stop reload

This little program writes into /tmp/counter the number of seconds since its start, and reports its events to daemons.log; it is also ready to be deployed to /etc/init.d or /etc/rc.d; started by root, it will drop priviledges to the daemon user, or, if you name the program 'foo' and user foo exists, to user foo. Far from being a UNIX guru, I am almost certain that I did some mistakes in the library, so I release it open-soure and welcome corrections. hdaemonize home: inspiration for the code:


  1. Hi Anton

    Just saw your comment at sneakymustard. I think it's great that you're making a library out of this. Creating daemons is probably one of those things which everyone who needs it writes his own private version, so this will benefit everyone!


  2. Thanks Andre! I will put it up on hackage after simplifying a bit.