[Haskell-cafe] How to daemonize a threaded Haskell program?

Donn Cave donn at avvanta.com
Sat Mar 5 21:43:44 CET 2011


Quoth Bas van Dijk <v.dijk.bas at gmail.com>,
...
> I understand why it's problematic to fork a process which is in the
> middle of running multiple simultaneous threads. However, in the case
> of a daemon the fork happens in the beginning of the program. So if I
> can manage to create a program that first daemonizes my process then
> starts the Haskell program, all is good.

type ProcessID = CInt
type Fd = CInt

foreign import ccall "fork" c_fork :: IO CInt
foreign import ccall "_exit" _exit :: CInt -> IO ()

fork :: IO Int -> IO ProcessID
fork fn = do
        pid <- c_fork
        if pid == 0
                then do
                        fn >>= _exit . fromIntegral
                        return 0 -- unused, I reckon
                else if pid > 0
                        then return pid
                        else throwErrno "fork"

System.PosixProcess (exitImmediately) is supposed to be "_exit".

I would not care to hazard a guess as to whether this will work
reliably for you.

If you figure out how to use your own custom C main() function,
I'd be interested to know.  I use separate C programs that
exec my Haskell programs.  My current GHC can't compile -via-C,
but if you can compile a minimal "main" module to C that way,
it probably calls hs_main() or something like that?  and you
could add your own xx_main() to the stack.

	Donn Cave, donn at avvanta.com



More information about the Haskell-Cafe mailing list