Home > Projects > Signal Capture
Sometimes it is useful to capture operating system signals from a Java program. Unfortunately, Java does not provide a standard means for capturing signals. However, in the sun.misc.* there is a class (SignalHandler) that can be used for this purpose. It should be noted that Sun does not recommend using the sun.* packages directly and it is possible that these classes might not be available in all versions of Java or from other vendors. Please read Sun's warning before using these classes.
Example
Create a handler, similar to an event listener, that will do something when the signal is received.
SignalHandler handler=new SignalHandler()
{
public void handle(Signal signal)
{
System.out.println("Do something...");
}
};
Register the signals of interest with the handler. A list of signals with descriptions can be found here.
Signal.handle(new Signal("INT"), handler);
Signal.handle(new Signal("TERM"), handler);
Download
- SignalCapture.java: example program that uses the SignalHandler class to capture SIGINT and SIGTERM.