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

查看:542
本文介绍了在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:


  • 程序正常退出,当最后一个非守护线程退出时或者当调用exit(等同于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 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指出的,关闭挂钩可以保证在VM正常关闭时运行但是如果VM进程强行终止,它们不会。这可能发生,如果本机代码拧紧,或者如果你强行杀死进程( 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天全站免登陆