Haskell running in the background does not redirect output to a file if the buffer mode is not NoBuffering

I have a Haskell program that periodically logs some data. When I run it as a background process, my logging instructions are not redirected to the log file unless I changed the buffering mode to NoBuffering. I do not understand why the default setting LineBufferingdoes not work.

Here is my test program:

import Control.Concurrent (forkIO, threadDelay)
import Control.Monad (forever)
import System.IO (BufferMode(..), hSetBuffering, stdout)

main :: IO ()
main = forever $ do
  -- hSetBuffering stdout NoBuffering
  threadDelay $ 1000 * 1000
  putStrLn "log"

When I run this program usually in the console, I get the expected output:

$ ./Main
log
log
log

Log output once per second. When I redirect it to a file, it also works as expected:

$ ./Main >log
^C
$ cat log
log
log
log

However, when I run it as a background process:

$ ./Main >log &
$ cat log

, , stdout NoBuffering.

hGetBuffering, , LineBuffering. , "log" , NoBuffering, ? .. , LineBuffering?

+4
1

. . , "".

NoBuffering - , LineBuffering , , .

, BlockBuffering, LineBuffering, . , stdout.

0

Source: https://habr.com/ru/post/1694627/


All Articles