module PipeNonBlockIO whereimport Control.Monad (void)import Control.Concurrentimport Control.Concurrent.MVarimport Data.Wordimport Foreign.C.Errorimport Foreign.C.Typesimport Foreign.Marshal.Allocimport Foreign.Marshal.Arrayimport Foreign.Ptrimport Foreign.Storableimport System.IO.FDforeign import ccall "unistd.h pipe" c_pipe :: Ptr CInt -> IO CIntforeign import ccall "unistd.h read" c_read :: CInt -> Ptr Word8 -> CInt -> IO CIntforeign import ccall "unistd.h write" c_write :: CInt -> Ptr Word8 -> CInt -> IO CIntforeign import ccall "fcntl.h fcntl" c_fcntl :: CInt -> CInt -> CInt -> IO CIntforeign import capi "fcntl.h value F_SETFL" fSETFL :: CIntforeign import capi "fcntl.h value O_NONBLOCK" oNONBLOCK :: CIntsetNonBlocking :: CInt -> IO ()setNonBlocking fd = throwErrnoIfMinus1_ "fcntl" $ c_fcntl fd fSETFL oNONBLOCKblockOnRead :: CInt -> IO Word8blockOnRead fd = alloca go where go p = do r <- c_read fd p 1 if r == 1 then peek p else do errno <- getErrno if errno == eAGAIN || errno == eWOULDBLOCK then do putStrLn "entering waitForReadFD" waitForReadFD (fromIntegral fd) go p else throwErrno "read"reader :: CInt -> MVar () -> IO ()reader fd done = do putStrLn "reader: waiting for data" b1 <- blockOnRead fd putStrLn $ "reader: received " ++ show b1 b2 <- blockOnRead fd putStrLn $ "reader: received " ++ show b2 putMVar done ()pipe :: IO (CInt, CInt)pipe = do allocaArray 2 $ \ fds -> do c_pipe fds rd <- peekElemOff fds 0 wr <- peekElemOff fds 1 return (rd, wr)main :: IO ()main = do (readFd, writeFd) <- pipe setNonBlocking readFd-- print (readFd, writeFd) done <- newEmptyMVar :: IO (MVar ()) forkIO $ reader readFd done threadDelay 1000000 -- let the other thread reach its blocking state alloca $ \ p -> do putStrLn "main: writing to pipe" poke p 42 c_write writeFd p 1 threadDelay 1000000 poke p 43 c_write writeFd p 1 takeMVar done