2012年5月更新(2年半后)
On current versions of Java this signal handling code fails because the “INT” signal is “reserved by the VM or the OS”.
Additionally, none of the other valid signal names actually fire when something requests the application to close (I just painstakingly tested all of the ones I could find out about…)
The shutdown hook mostly works but we find that in our case it isn’t firing, so the next step is obviously to resort to registering a handler behind the JVM’s back
原始答案(2009年9月)
一个ShutdownHook应该能够处理这种情况
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
// what you want to do
}
}));
(含caveats)
也可以看看:
作为简单信号处理的说明:
public class Aaarggh {
public static void main(String[] args) throws Exception {
Signal.handle(new Signal("INT"), new SignalHandler () {
public void handle(Signal sig) {
System.out.println(
"Aaarggh, a user is trying to interrupt me!!");
System.out.println(
"(throw garlic at user, say `shoo, go away')");
}
});
for(int i=0; i<100; i++) {
Thread.sleep(1000);
System.out.print('.');
}
}
}