java 信号_如何在Java中正常处理SIGKILL信号

本文探讨了Java程序如何处理关闭事件,尤其是SIGTERM(kill-15)与SIGKILL(kill-9)的区别。在Java中,通过添加shutdown hook可以优雅地关闭程序,但kill-9无法触发这些hook。建议使用kill-15来确保程序执行关闭流程。在某些极端情况下,如外部SIGKILL信号,虚拟机可能不干净地终止。解决方案包括使用监控程序或包装脚本来确保程序关闭的优雅性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

处理这个除kill -9以外的任何方法将注册一个

shutdown钩。如果可以使用(SIGTERM)kill -15,关闭挂接将工作。 (SIGINT)kill -2 DOES导致程序正常退出并运行关闭挂接。

Registers a new virtual-machine

shutdown hook.

The Java virtual machine shuts down in

response to two kinds of events:

06000

when the exit (equivalently,

System.exit) method is invoked, or

06001

interrupt, such as typing ^C, or a

system-wide event, such as user logoff

or system shutdown.

我试过下面的测试程序在OSX 10.6.3和kill -9它没有运行关闭挂钩,没有想到它会。在kill -15它每次运行关闭挂钩。

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

}

}

}

没有任何办法真正优雅地处理任何程序中的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的唯一真正的选择是让另一个观察程序监视你的主程序,或使用包装器脚本。你可以使用一个shell脚本,轮询ps命令在列表中查找你的程序,并在它消失时相应地执行。

#!/bin/bash

java TestShutdownHook

wait

# notify your other app that you quit

echo "TestShutdownHook quit"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值