我怎样才能“拦截"CLI 应用程序中的 Ctrl+C? [英] How can I "intercept" Ctrl+C in a CLI application?

查看:25
本文介绍了我怎样才能“拦截"CLI 应用程序中的 Ctrl+C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何拦截 Ctrl+C(通常会终止进程)在 CLI(命令行界面)Java 应用程序中?

How can I intercept Ctrl+C (which normally would kill the process) in a CLI (command line interface) Java application?

是否存在多平台解决方案(Linux、Solaris、Windows)?

Does a multi-platform solution exist (Linux, Solaris, Windows)?

我正在使用 ConsolereadLine(),但如果有必要,我可以使用其他方法从标准输入读取字符.

I'm using Console's readLine(), but if necessary, I could use some other method to read characters from standard input.

推荐答案

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() { /*
       my shutdown code here
    */ }
 });

这应该能够拦截信号,但只是作为JVM完全关闭之前的一个中间步骤,所以它可能不是你所关心的.

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.

需要使用SignalHandler(sun.misc.SignalHandler)来拦截触发的SIGINT信号通过 Ctrl+C(在 Unix 和 Windows 上).
请参阅这篇文章(pdf,第 8 页和9).

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

这篇关于我怎样才能“拦截"CLI 应用程序中的 Ctrl+C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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