gpt4 book ai didi

java - 在 Java 中捕获 SIGINT

转载 作者:IT老高 更新时间:2023-10-28 20:48:02 24 4
gpt4 key购买 nike

在不使用 JNI 的情况下,在 java 中捕获终止信号的最佳方法是什么。我确实发现了 sun.misc.Signal 和 sun.misc.SignalHandler 以及在未来版本中可能被删除的警告。

使用 JNI 调用 c lib 是我唯一的选择吗?

最佳答案

处理这个问题的方法是注册一个 shutdown钩。如果使用 (SIGINT) kill -2 将导致程序正常退出并运行关闭 Hook 。

Registers a new virtual-machine shutdown hook.

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 ^C, or a system-wide event, such as user logoff or system shutdown.

我在 OSX 10.6.3 上尝试了以下测试程序,在 kill -9 上它确实 NOT 运行了关闭 Hook ,但我认为它不会。在 kill -15 上,它DOES 每次都运行关闭 Hook 。

public class TestShutdownHook
{
public static void main(final String[] args) throws InterruptedException
{
Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
System.out.println("Shutdown hook ran!");
}
});

while (true)
{
Thread.sleep(1000);
}
}
}

这是编写自己的文档的方法 signal handlers这不是 Java 中的关闭钩子(Hook)。成为 warned com.sun.misc 打包并且不受支持,并且可能随时更改或消失,并且可能仅存在于 Sun JVM 中。

关于java - 在 Java 中捕获 SIGINT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2541475/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com