Consider something like this:
...
handleShutdown :: ThreadId -> IO ()
handleShutdown tid = doSomethingFunny >> throwTo tid ExitSuccess
main = do
...
installHandler sigTERM (Catch $ myThreadId >>= handleShutdown) Nothing
forever $ do
stuff
...
If sigINT
(Ctrl+C) is handled in this manner, the process finishes nicely. However, it seems like sigTERM
is being used by Haskell internally and the code above doesn't exit from the main process at all. Is there a way to exit the process from a sigTERM
handler without using an MVar
and a custom loop? I couldn't find any information on the sigTERM
handling anywhere (didn't read ghc sources, that's just too much for me to handle).
Update:
The following works:
main = do
...
tid <- myThreadId -- This moved out of the Catch handler below.
installHandler sigTERM (Catch $ handleShutdown tid) Nothing
forever $ do
stuff
...
Signal handlers can be specified for all but two signals (SIGKILL and SIGSTOP cannot be caught, blocked or ignored). If the signal reports an error within the program (and the signal is not asynchronous), the signal handler can terminate by calling abort() , exit() , or longjmp() .
SIGTERM (Exit Code 143) vs SIGKILL (Exit Code 137) SIGTERM (Unix signal 15) is a “polite” Unix signal that kills the process by default, but can be handled or ignored by the process. This gives the process a chance to complete essential operations or perform cleanup before shutting down.
The SIGTERM signal is a generic signal used to cause program termination. Unlike SIGKILL , this signal can be blocked, handled, and ignored. It is the normal way to politely ask a program to terminate.
SIGTERM. (signal 15) is a request to the program to terminate. If the program has a signal handler for SIGTERM that does not actually terminate the application, this kill may have no effect. This is the default signal sent by kill. SIGKILL.
Sorry for short answer, but on mobile.
You want to run myThreadId from outside of the handler itself to get the main thread's ID. You're currently getting the ID of the signal handler itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With