Skip to content

Instantly share code, notes, and snippets.

@parsonsmatt
Created October 11, 2022 19:00
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 parsonsmatt/1a76291afd1db064bb70a7fd67935074 to your computer and use it in GitHub Desktop.
Save parsonsmatt/1a76291afd1db064bb70a7fd67935074 to your computer and use it in GitHub Desktop.
{-# language OverloadedStrings, NumericUnderscores, ImportQualifiedPost #-}
module Lib where
import Data.Typeable
import Control.Monad
import Prelude hiding (log)
import Data.Text (Text)
import Data.Text qualified as Text
import Say
import UnliftIO.Concurrent
import UnliftIO.Exception
import System.Posix.Process
import System.Posix.Signals qualified as Posix (Handler (Catch), installHandler, sigTERM)
import System.Exit (ExitCode(..))
log :: Text -> IO ()
log msg = do
tid <- myThreadId
say $ mconcat
[ "[", Text.pack $ show tid, "]\t\t"
, msg
]
tshow :: Show a => a -> Text
tshow = Text.pack . show
someFunc :: IO ()
someFunc = do
log "Starting App"
mainThread <- myThreadId
void (Posix.installHandler Posix.sigTERM (Posix.Catch (shutdown mainThread)) Nothing)
procId <- getProcessID
log $ mconcat ["ProcessID: ", tshow procId]
forkFinally (do
tid <- myThreadId
void (Posix.installHandler Posix.sigTERM (Posix.Catch (shutdown tid)) Nothing)
forever loop
) $ \eerr ->
case eerr of
Left (SomeException err) -> do
log $ mconcat ["Received exception: ", tshow err]
log $ mconcat ["Exception type: ", tshow (typeOf err)]
Right () ->
log "Exited successfully"
forever loop `finally` log "Exiting with Finally"
where
loop = do
threadDelay 1_000_000
log "Waiting . . ."
shutdown tid = do
log "Shutting down gracefully"
throwTo tid ExitSuccess
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment