87

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.

Jasper
  • 2,166
  • 4
  • 30
  • 50
ivan_ivanovich_ivanoff
  • 19,113
  • 27
  • 81
  • 100

4 Answers4

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

Abhishek
  • 6,912
  • 14
  • 59
  • 85
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • 5
    @MartijnCourteaux That happens after five years ;) I have found a similar source on that topic and have changed the link accordingly. – VonC Apr 11 '14 at 14:06
  • @VonC - It's Dead again – Gurwinder Singh Dec 03 '17 at 12:27
  • @GurV Which link? The edit I made in April 2014 (https://stackoverflow.com/revisions/18adb35b-62a1-4266-b87d-9da49f81d70a/view-source) is still valid: you can still download the pdf file.. – VonC Dec 03 '17 at 13:24
17

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.

akf
  • 38,619
  • 8
  • 86
  • 96
8

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

Chriki
  • 15,638
  • 3
  • 51
  • 66
Amber
  • 507,862
  • 82
  • 626
  • 550
4

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.

Henning
  • 1,515
  • 1
  • 14
  • 24