5

I'm trying to do some pre-shutdown cleanup when a SIGINT is sent to my Java application, using the sun.misc.Signal and sun.misc.SignalHandler classes.

It appears when I register my handler the default behavior no longer occurs. But there is a SignalHandler.SIG_DFL field containing "The default signal handler". First of all, is the behavior of the default handler documented anywhere? Secondly, should I prefer the following pattern when implementing my own handlers?

SignalHandler handler = new SignalHandler() {
    public void handle(Signal sig) {
      ... // handle SIGINT
      SignalHandler.SIG_DFL.handle(sig);
    }
};

Edit: I am aware the sun.misc package is not portable, and that shutdown hooks are the more robust way to deal with application termination. Suffice to say I am aware of these features, and have a need to handle signals directly. To my knowledge, sun.misc.Signal is the correct way to do this.

dimo414
  • 47,227
  • 18
  • 148
  • 244
  • I'm not sure about how Java in particular handles signals, but I believe it is consistent with the UNIX programming environment; in that case you can see the default behavior for each signal in `man signal` (in Linux, this is in Section 7; Mac OS seems to have it in Section 3). You probably don't want to invoke the default handler for `SIGINT` unless you want to terminate (the default action for `SIGINT`). – Filipe Gonçalves Aug 17 '15 at 20:12
  • In my testing, it appears the default handler kills (not interrupts) the `main` Java thread, leaving other non-daemon threads running. But I'm hesitant to rely on my likely incomplete and/or flawed observations. – dimo414 Aug 17 '15 at 20:20

2 Answers2

0

As detailed in a related question, you should not call SignalHandler.SIG_DFL in your SignalHandler, as you'll cause a SEGV. In fact, the JVM doesn't use SIG_DFL either (for INT, TERM, and HUP).

Under the covers all Java does when it receives any of those signals is call System.exit(). So if you want to replicate the default behavior, simply call System.exit() yourself. Obviously if you don't want to exit in response to the signal, there's no need to call the old/default signal handler at all.

Warning: this is undocumented behavior. It's unlikely but entirely possible that future releases of Java could change this behavior.

Community
  • 1
  • 1
dimo414
  • 47,227
  • 18
  • 148
  • 244
-1

Answering your question: no you don't need (or want) to call default handler. But using this class is not portable. You should install shutdown hook:

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() {
        //your graceful shutdown procedure here
    }
});
krzydyn
  • 1,012
  • 9
  • 19