How can I “intercept” Ctrl + C in a CLI application?

How can I intercept Ctrl + C (which would normally kill a process) in the CLI (command line interface) of a Java application?

Is there a multi-platform solution (Linux, Solaris, Windows)?

I use Console readLine() , but if necessary I can use some other method to read characters from standard input.

+77
java command-line command-line-interface copy-paste stdin
Aug 01 '09 at 8:29
source share
4 answers
 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 shuts down completely, so maybe this is not what you need.

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

+113
Aug 01 '09 at 8:40
source share

I assume that you want to gracefully shut down and not short-circuit the shutdown process. If my assumption is correct, then you should look at Shutdown Hooks .

+15
Aug 01 '09 at 8:35
source share

In order to be able to process Ctrl + C without any stops, you will need to use some form of signal processing (since the input Ctrl + C is not actually passed directly to your application, but instead it is processed by the OS that generates SIGINT, which is then passed to Java .

For more information on signal processing, see http://www.oracle.com/technetwork/java/javase/signals-139944.html .

(If you just want to gracefully shut down, akf answer will suffice.)

+7
Aug 01 '09 at 8:39
source share

Some links on how to handle SIGTERM are the signal that the program receives 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/

This should work on POSIX operating systems, that is, Mac and Unix should work, on windows I’m not sure, I remember that it is also compatible with POSIX, but can be very different with different versions.

+4
Aug 01 '09 at 8:42
source share



All Articles