在 Java 中捕获 Ctrl+C [英] Catching Ctrl+C in Java

查看:25
本文介绍了在 Java 中捕获 Ctrl+C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

您可以附上 shutdown hook 到 VM,只要 VM 关闭就会运行:

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

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

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

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

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

虚拟机响应用户中断而终止,例如键入 Ctrl+C 或系统范围的事件,例如作为用户注销或系统关闭.

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.

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

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.

这篇关于在 Java 中捕获 Ctrl+C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆