Thursday, August 14, 2008

Intercepting SIGTERM

The 'proper' way to terminate a java process on unix is by sending SIGTERM, waiting a bit, and then sending SIGKILL. This gives java a chance to clean - using Runtime.getRuntime().getShutdownHook().

If you want to intercept this and do some early cleanup, before letting the others do theirs you need to use sun.misc.Signal - which can also be used to intercept other signals.

Things to do in a shutdownHook ? Flush the logs, finish important background processes and much more.

Code to intercept the signal:

oldSigTERM = Signal.handle(new Signal("TERM"),
new SignalHandler() {
public void handle(Signal signal) {
System.err.println("Quit using SIGTERM hook");
notificationHandler.prepareToQuit();
if (oldSigTERM != null) {
oldSigTERM.handle(signal);
}
}
});

1 comment:

Julien said...

Hello Costin,

Sorry for that behavior but my comment is not about this post but one you made 3 years ago I read at http://www.webweavertech.com/costin/archives/000412.html

I am desperately searching a solution to get RELIABLY HTTP Requests (as a Server) and Responses (as a Client) as strings in my Javascript but is still screwed by this f***ing nsIScriptableInputStream.read() method that keeps on returning randomly truncated text.

In your post, you seemed to find a solution, could you share it?

Thanks in advance,

Julien