如何在 CLI 应用程序中“拦截”Ctrl + C?

我如何能 拦截 Ctrl + C(通常会杀死进程) 在 CLI (命令行接口) Java 应用程序中?

是否存在多平台解决方案(Linux、 Solaris、 Windows) ?

我使用的是 ConsolereadLine(),但如果必要的话,我可以使用其他方法 从标准输入中读取字符。

66485 次浏览

I am assuming you want to shutdown gracefully, and not do short circuit the shutdown process. If my assumption is correct, then you should look at Shutdown Hooks.

In order to be able to handle Ctrl+C without shutting down for some reason, you'll need to use some form of signal handling (since the Ctrl+C input isn't actually passed directly to your application, but instead is handled by the OS which generates a SIGINT that is then passed to Java.

See http://www.oracle.com/technetwork/java/javase/signals-139944.html for details on signal handling.

(If you're just wanting to gracefully shutdown, akf's answer will suffice.)

Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() { /*
my shutdown code here
*/ }
});

This should be able to intercept the signal, but only as an intermediate step before the JVM completely shutdowns itself, so it may not be what you are looking after.

You need to use a SignalHandler (sun.misc.SignalHandler) to intercept the SIGINT signal triggered by a Ctrl+C (on Unix as well as on Windows).
See this article (pdf, page 8 and 9).

Some links about how to handle SIGTERM - that is the signal the program is getting on the OS side:

http://blog.webinf.info/2008/08/intercepting-sigterm.html

http://java.sun.com/javase/6/webnotes/trouble/TSG-VM/html/signals.html

http://www.ibm.com/developerworks/java/library/i-signalhandling/

That should work on POSIX operating systems - that is, Mac and Unix should work, on windows I'm not sure, I remember hearing it is also POSIX compatible to some extent, but might varty a lot with different versions.