处理这个除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"