gpt4 book ai didi

java - 如何优雅地处理 Java 中的 SIGKILL 信号

转载 作者:IT老高 更新时间:2023-10-28 11:23:53 28 4
gpt4 key购买 nike

当程序收到终止信号时,您如何处理清理工作?

例如,我连接的一个应用程序希望任何第三方应用程序(我的应用程序)在注销时发送 finish 命令。当我的应用程序被 kill -9 销毁时,发送该 finish 命令最好的说法是什么?

edit 1:kill -9 无法被捕获。谢谢你们纠正我。

edit 2:我猜这种情况是当一个调用只是 kill 这与 ctrl-c 相同

最佳答案

任何语言的任何程序不可能处理 SIGKILL。因此,即使程序有缺陷或恶意,也始终可以终止程序。但是 SIGKILL 并不是终止程序的唯一方法。另一种是使用 SIGTERM。程序可以处理那个信号。程序应该通过控制但快速的关闭来处理信号。当计算机关闭时,关闭进程的最后阶段会向每个剩余进程发送一个 SIGTERM,给这些进程几秒钟的宽限期,然后向它们发送一个 SIGKILL。

对于kill -9 以外的任何other 的处理方法是注册一个shutdown。钩。如果您可以使用 (SIGTERM) kill -15,则关闭 Hook 将起作用。 (SIGINT) kill -2 DOES 导致程序正常退出并运行关闭 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(String[] args) throws InterruptedException
{
Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
System.out.println("Shutdown hook ran!");
}
});

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

没有任何方法可以真正优雅地处理任何程序中的 kill -9

In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly. This occurs when the virtual machine is terminated externally, for example with the SIGKILL signal on Unix or the TerminateProcess call on Microsoft Windows.

处理 kill -9 的唯一真正选择是让另一个监视程序监视您的主程序消失或使用包装脚本。您可以使用一个轮询 ps 命令以在列表中查找您的程序并在它消失时采取相应措施的 shell 脚本来完成此操作。

#!/usr/bin/env bash

java TestShutdownHook
wait
# notify your other app that you quit
echo "TestShutdownHook quit"

关于java - 如何优雅地处理 Java 中的 SIGKILL 信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2541597/

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