Catching a specific SIGNAL/Interrupt in Java

You can use the undocumented class sun.misc.Signal. But beware of using the Sun packages.

This program allows you to catch any of the following signals:

   Windows:
      	ABRT	SIGABRT
	FPE 	SIGFPE
    	SEGV	SIGSEGV
	INT	SIGINT
	TERM	SIGTERM
	ILL	SIGILL


   Solaris/Linux:
	HUP	SIGHUP
	INT	SIGINT
	QUIT	SIGQUIT
	ILL	SIGILL
	TRAP	SIGTRAP
	ABRT	SIGABRT
	IOT	SIGIOT (*)
	EMT	SIGEMT (*)
	FPE	SIGFPE
	KILL	SIGKILL
	BUS	SIGBUS
	SEGV	SIGSEGV
	SYS	SIGSYS
	PIPE	SIGPIPE
	ALRM	SIGALRM
	TERM	SIGTERM
	STKFLT	SIGSTKFLT
	USR1	SIGUSR1
	USR2	SIGUSR2
	CHLD	SIGCHLD
	PWR	SIGPWR
	WINCH	SIGWINCH
	URG	SIGURG
	POLL	SIGPOLL
	IO	SIGIO
	STOP	SIGSTOP
	TSTP	SIGTSTP
	CONT	SIGCONT
	TTIN	SIGTTIN
	TTOU	SIGTTOU
	VTALRM	SIGVTALRM
	PROF	SIGPROF
	XCPU	SIGXCPU
	XFSZ	SIGXFSZ
	UNUSED	SIGUNUSED
	SWI	SIGSWI

The example program (Linux/Solaris) demonstrates to catch and perform a System.exit only with a SIGTERM. A SIGHUP will not cause the program to exit.

Main.java:

import sun.misc.Signal;
import sun.misc.SignalHandler;
import java.lang.reflect.*;
 
public class Main
{
   public static void main(String []args) {
      DebugSignalHandler.listenTo("HUP");
      DebugSignalHandler.listenTo("INT");
      DebugSignalHandler.listenTo("KILL");
      DebugSignalHandler.listenTo("TERM");
 
      while (true) {
         try {
            Thread.sleep(1000);
         }
         catch(InterruptedException e) {
         }
      }
   }
}
 
class DebugSignalHandler implements SignalHandler
{
   public static void listenTo(String name) {
      Signal signal = new Signal(name);
      Signal.handle(signal, new DebugSignalHandler());
   }

   public void handle(Signal signal) {
      System.out.println("Signal: " + signal);
      if (signal.toString().trim().equals("SIGTERM")) {
         System.out.println("SIGTERM raised, terminating...");
         System.exit(1);
      }
   }
}