DupTo oddities related to STDOUT

I am writing code to demonstrate the process. Naturally, I want to be able to redirect STDOUT.

However, as soon as I switch file descriptors, the Haskell print functions do not write anything to my file or console, but the call fdWrite

on the updated file descriptor stdOutput

works as intended.

As a side note, if I use any Haskell print function (print, hPutStr, etc.) before me daemonize'

, everything works as intended (stdout is written to my file)

How do I fix this problem?

This is how I daemonize:

daemonize' :: Maybe String -> Maybe String -> IO () -> IO () 
daemonize' outpath errpath program = do
  forkProcess $ do
    createSession
    forkProcess $ do
      redirectIO outpath errpath
      blockSignal sigHUP
      program
    exitImmediately ExitSuccess
  exitImmediately ExitSuccess

blockSignal :: Signal -> IO () 
blockSignal sig = installHandler sig Ignore Nothing >> (return ())

      

This is the code that redirects STDOUT:

redirectIO :: Maybe String -> Maybe String -> IO ()
redirectIO outpath errpath = do
  dnull <- openFd "/dev/null" ReadWrite Nothing defaultFileFlags
  closeFd stdInput >> dupTo dnull stdInput
  case outpath of
    Nothing -> closeFd stdOutput >> dupTo dnull stdOutput >> return ()
    Just out -> do
      fdWrite stdOutput "HELLO"
      fd <- openFd out ReadWrite Nothing defaultFileFlags
      setFdOption fd AppendOnWrite True
      dupTo fd stdOutput
      closeFd fd
  case errpath of
    Nothing -> closeFd stdError >> dupTo dnull stdError >> return ()
    Just err -> do
      fd <- openFd err ReadWrite Nothing defaultFileFlags
      setFdOption fd AppendOnWrite True
      dupTo fd stdError
      closeFd fd

      

+3


source to share


1 answer


Until I have solved my problem, these problems are stdout

not redirected correctly, only when my program is daemonized as above; the redirection stdout

, while the program is not daemonized, works as expected, writing to the file I specify.

UPDATE 7.31.15:



It turns out that the stdout descriptor was not buffered correctly. After I did the buffering stdout

and stderr

Handle

everything worked as intended.

hSetBuffering stdout NoBuffering
hSetBuffering stderr NoBuffering -- for consistency
hSetBuffering stdin  NoBuffering -- for consistency

      

+2


source







All Articles