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

ivan_ivanovich_ivanoff picture ivan_ivanovich_ivanoff · Aug 1, 2009 · Viewed 63.1k times · Source

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

Does a multi-platform solution exist (Linux, Solaris, Windows)?

I'm using Console's readLine(), but if necessary, I could use some other method to read characters from standard input.

Answer

VonC picture VonC · Aug 1, 2009
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).