Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I exit the program from a sigTERM handler?

Tags:

haskell

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
    ...
like image 347
Jan Synáček Avatar asked Apr 27 '17 13:04

Jan Synáček


People also ask

How do I get out of signal handler?

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() .

Does SIGTERM call exit?

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.

Can SIGTERM be handled?

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.

What is SIGTERM handler?

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.


1 Answers

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.

like image 174
Michael Snoyman Avatar answered Oct 18 '22 00:10

Michael Snoyman