Catching Ctrl+C in Java

Catching Ctrl+C in Java

You can attach a shutdown hook to the VM which gets run whenever the VM shuts down:

The Java virtual machine shuts down in response to two kinds of events:

  • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or

  • The virtual machine is terminated in response to a user interrupt, such as typing Ctrl+C, or a system-wide event, such as user logoff or system shutdown.

The thread you pass as shutdown hook has to follow several rules, though, so read the linked documentation carefully to avoid any problems. This includes ensuring thread-safety, quick termination of the thread, etc.

Also, as commenter Jesper points out, shutdown hooks are guaranteed to run on normal shutdown of the VM but if the VM process is terminated forcibly they don't. This can happen if native code screws up or if you forcibly kill the process (kill -9, taskkill /f).

But in those scenarios all bets are off anyway, so I wouldn't waste too much thought on it.

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

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

How does CTRL-C work with Java program

According to the javadocs, the registered shutdown hooks are called in an unspecified order when the JVM starts shutting down; e.g. in response to a CTRL-C.

Application threads are not "stopped" in any well defined way. Indeed, they could continue running up right until the process exits.

If you want your threads to be shut down in an orderly fashion, you need to do something in a shutdown hook to cause this to happen. For example, a shutdown hook could call Thread.interrupt() to tell worker threads to stop what they are doing ... and call join() to make sure that it has happened.



Related Topics



Leave a reply



Submit