module Daemon where
import System.Directory
import System.Exit
import System.Posix.Files
import System.Posix.IO
import System.Posix.Process
import System.Posix.Signals
daemonize :: IO () -> IO ()
daemonize f = do
omask <- setFileCreationMask 0
pid <- forkProcess child
exitSuccess
where
child :: IO ()
child = do
sess <- createSession
ohandler <- installHandler sigHUP Ignore Nothing
forkProcess grandChild
exitSuccess
grandChild :: IO ()
grandChild = do
setCurrentDirectory "/"
devNullFd <- openFd "/dev/null" ReadWrite Nothing defaultFileFlags
mapM_ (closeAndDupTo devNullFd) [stdInput, stdOutput, stdError]
f
where
closeAndDupTo dupFd fd = closeFd fd >> dupTo dupFd fd