module Daemon where import System Directory import System Exit import

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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