Skip to content

Instantly share code, notes, and snippets.

@CarstenKoenig
Created August 11, 2017 20:34
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 CarstenKoenig/890638d76d2892c5a05235da8f7bfc62 to your computer and use it in GitHub Desktop.
Save CarstenKoenig/890638d76d2892c5a05235da8f7bfc62 to your computer and use it in GitHub Desktop.
handling sigINT and sigTERM in Haskell (posix)
module Main where
import Control.Concurrent (threadDelay, MVar, newEmptyMVar, putMVar, tryTakeMVar)
import Data.Maybe (isJust)
import System.IO (hSetBuffering, BufferMode(NoBuffering), stdout)
import System.Posix.Signals (installHandler, Handler(Catch), sigINT, sigTERM)
main :: IO ()
main = do
stop <- newEmptyMVar
hSetBuffering stdout NoBuffering
_ <- installHandler sigINT (Catch $ onSigInt stop) Nothing
_ <- installHandler sigTERM (Catch $ onSigTerm stop) Nothing
loop stop
loop :: MVar () -> IO ()
loop stop = do
stopRequested <- isJust <$> tryTakeMVar stop
if stopRequested
then putStrLn "bye!"
else do
threadDelay 1000000
putStr "."
loop stop
onSigInt :: MVar () -> IO ()
onSigInt stop = do
putStrLn "got sigINT"
putMVar stop ()
onSigTerm :: MVar () -> IO ()
onSigTerm stop = do
putStrLn "got sigTERM"
putMVar stop ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment