Skip to content

Help needed: GHC.Conc.threadWaitRead behavior on MacOS

Greetings,

I'm trying to understand why threadWaitRead seems to be behaving differently on MacOS than it does on Linux (for various versions of GHC 8 and 9 that I have tried) for the following demonstration program. Here's the source:

  module Main where

  import Control.Monad (forever)
  import GHC.Conc (threadWaitRead)
  import System.IO (openFile, stdin, IOMode(..), BufferMode(..), hSetBuffering)
  import System.Posix (FdOption(..), setFdOption, fdRead, handleToFd)
  import System.Exit (exitFailure)
  import System.Environment (getArgs)

  main :: IO ()
  main = do
      args <- getArgs
      handle <- case args of
          ["stdin"] -> return stdin
          ["tty"]   -> openFile "/dev/tty" ReadMode
          _         -> putStrLn "Usage: minimal <stdin|tty>" >> exitFailure

      hSetBuffering handle NoBuffering
      ttyFd <- handleToFd handle
      setFdOption ttyFd NonBlockingRead False

      forever $ do
          putStrLn "Calling threadWaitRead"
          threadWaitRead ttyFd
          putStrLn "Calling fdRead"
          (b, _) <- fdRead ttyFd 16
          putStrLn $ "read: " <> show b
  • On Linux, running this program with either argument (stdin or tty) shows the same behavior: the program is initially blocked at threadWaitRead, and as soon as a keypress is available on stdin, the program wakes up, calls fdRead, and immediately reads and prints the available character. This is the behavior I expected to see, namely that threadWaitRead would block until data is available (as documented) and the subsequent call to fdRead would always return immediately.
  • On MacOS, running this program with the argument stdin has the exact same behavior as both arguments produce on Linux. However, running this program with the argument tty results in a situation I don't understand: the initial call to threadWaitRead returns immediately despite there being no data to read, and then the program blocks at fdRead.

What am I missing here?

Thanks!

To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information