Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 960
ivan_ivanovich_ivanoff Avatar asked Aug 01 '09 08:08

ivan_ivanovich_ivanoff


People also ask

How to catch Ctrl c in Java?

Signal. handle(new Signal("INT"), // SIGINT signal -> System. out. println("Interrupted by Ctrl+C"));


2 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 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).

like image 138
VonC Avatar answered Sep 25 '22 01:09

VonC


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.

like image 29
akf Avatar answered Sep 26 '22 01:09

akf