Wednesday, October 20, 2010

Java signal handler implementation

Here is a Java signal handler implementation. The signal will be handled even though Thread.sleep is running.
import sun.misc.Signal;
import sun.misc.SignalHandler;

public class Test
{
   public static void main(String[] args)
   {
       SignalHandler signalHandler = new SignalHandler() {
           public void handle(Signal signal) {
               System.err.println("Exiting because of signal: " + signal);
               System.exit(1);
           }
       });
       Signal.handle(new Signal("TERM"), signalHandler);
       Signal.handle(new Signal("INT"), signalHandler);

       try {
           Thread.sleep(50000);
       }
       catch (InterruptedException e) {
           System.err.println("Interrupted");
       }
   }
}