Catching Ctrl+C in Java

Viewed 82863

Is it possible to catch the Ctrl+C signal in a java command-line application? I'd like to clean up some resources before terminating the program.

3 Answers

The top answer suggests using a shutdown hook. Shutdown hooks are far more trouble than they are worth. They run in an indeterminate order, and libraries you depend upon may add their own shutdown hooks, which may mean that something your own shutdown hook depends upon may be de-initialized before your shutdown hook runs. Save yourself the headache, and use a signal handler:

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

Signal is currently sun.misc.Signal, which means it will be deprecated -- but what it's being replaced with is currently named jdk.internal.misc.Signal, so until the Java team figure out how to publicly expose signal handlers in a non-internal way, beware that this call may go away. For now though (as of JDK 11), sun.misc.Signal still exists.

Related