Skip to content
Advertisement

How do I trigger the default signal handling behavior?

In my Java application I want to capture SIGINTs, do some pre-processing, and then let the default behavior (process termination) run. I would think I could do something like this:

JavaScript

However when I send at SIGINT to this application, I get a SEGV:

JavaScript

It seems SignalHandler.SIG_DFL is not meant to be called directly (even from other signal handling code). So how can I manually trigger it?

Alternatively, how can I manually replicate the behavior of SIG_DFL? It appears to be equivalent to:

JavaScript

but I don’t see any documentation to that effect.


Another way to phrase my question:

In practice* is there a difference between these two code blocks?

A)

JavaScript

B)

JavaScript

*I know undocumented behavior could change at any time, but it’s unlikely that the JVM’s exit behavior will change mid-version. An answer that simply details what happens now is acceptable, in practice.

Advertisement

Answer

Credit for originally noticing this goes to RealSkeptic, but I wanted to expand on it in an answer.

The default behavior for SIGINT, SIGTERM, and SIGHUP is not, in fact, SignalHandler.SIG_DFL. Instead, the java.lang.Terminator class registers a SignalHandler that simply calls Shutdown.exit():

JavaScript

You can capture this SignalHandler by calling Signal.handle() (since it returns the old handler), or you can simply define your own handler that calls System.exit() which will do the same thing.

Note that Terminator‘s call to Shutdown.exit() is not exactly the same as System.exit(). The former is package-private, meaning you can’t call it directly. If a security manager prevents you from calling System.exit(), you’ll have to capture the original handler and reuse it.

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

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement