Created
August 11, 2017 20:34
-
-
Save CarstenKoenig/890638d76d2892c5a05235da8f7bfc62 to your computer and use it in GitHub Desktop.
handling sigINT and sigTERM in Haskell (posix)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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