Skip to content

Instantly share code, notes, and snippets.

@HirotoShioi
Created February 22, 2019 02:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HirotoShioi/443ab877898efa5f85cabd89b62d6bfd to your computer and use it in GitHub Desktop.
Save HirotoShioi/443ab877898efa5f85cabd89b62d6bfd to your computer and use it in GitHub Desktop.
import Control.Exception
import Control.Monad (forever, void)
import Data.Char (toUpper)
import GHC.IO.Handle.FD (fdToHandle)
import Prelude
import System.Exit
import System.IO (BufferMode (..), hGetLine, hPrint,
hPutStrLn, hSetBuffering, hClose)
import System.Posix.Process (exitImmediately, forkProcess)
import System.Process (createPipe, createPipeFd)
import Text.Read (readEither)
-- | Example using two processes
--
-- We want server/client to read only the messages that each should care about
-- In order to realize this, we need two proccesses with each of them providing
-- read/write handle.
--
-- These processes will then pass each others handle respectively and use it to
-- communicate with each other.
--
-- Server will take client's write handle and server's read handle.
--
-- Client will take server's write handle and client's read handle.
--
-- This allows the two proccesses to send the message to the other while
-- reading the response that other had sent.
exampleWithProcess :: IO ()
exampleWithProcess = do
(clientReadHndl, clientWriteHndl) <- createPipe
hSetBuffering clientReadHndl LineBuffering
hSetBuffering clientWriteHndl LineBuffering
processId <- forkProcess $ do
(serverReadHndl, serverWriteHndl) <- createPipe
hSetBuffering serverReadHndl LineBuffering
hSetBuffering serverWriteHndl LineBuffering
hPutStrLn serverWriteHndl "Ping"
hPutStrLn serverWriteHndl "Pong"
finally
(forever $ do
msg <- hGetLine serverReadHndl
hPutStrLn clientWriteHndl (map toUpper msg)
)
(exitImmediately ExitSuccess)
msg <- hGetLine clientReadHndl -- PING
msg2 <- hGetLine clientReadHndl -- PONG
print msg
print msg2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment