在 Java 中捕获 Ctrl+C

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1611931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:48:32  来源:igfitidea点击:

Catching Ctrl+C in Java

javacommand-linecontrol-c

提问by Pierre

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

是否可以在 java 命令行应用程序中捕获Ctrl+C信号?我想在终止程序之前清理一些资源。

采纳答案by Joey

You can attach a shutdown hookto 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.

Java 虚拟机关闭以响应两种事件:

  • 程序正常退出,当最后一个非守护线程退出或调用退出(相当于 System.exit)方法时,或

  • 虚拟机响应用户中断(例如键入Ctrl+ C)或系统范围的事件(例如用户注销或系统关闭)而终止。

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

此外,正如评论者 Jesper 指出的那样,关闭挂钩保证在 VM 正常关闭时运行,但如果 VM 进程被强制终止,它们不会。如果本机代码出错或者您强行终止进程 ( kill -9, taskkill /f) ,就会发生这种情况。

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

但在这些情况下,无论如何都不会下注,所以我不会在这上面浪费太多想法。

回答by bkomac

Just for quick console testing purposes...

仅用于快速控制台测试目的...

Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                Thread.sleep(200);
                System.out.println("Shutting down ...");
                //some cleaning up code...

            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                e.printStackTrace();
            }
        }
    });