用Java捕获SIGINT [英] Capture SIGINT in Java
问题描述
在不使用JNI的情况下在Java中捕获终止信号的最佳方法是什么.我确实发现了sun.misc.Signal和sun.misc.SignalHandler以及在将来的发行版中可能被删除的警告.
What is the best way to capture a kill signal in java without using JNI. I did discover the sun.misc.Signal and the sun.misc.SignalHandler and the warning of the possibility of being removed in the future releases.
使用JNI调用c lib是我唯一的选择吗?
Would using JNI to call a c lib be the only option i have?
推荐答案
The way to handle this would be to register a shutdown hook. If you use (SIGINT) kill -2
will cause the program to gracefully exit and run the shutdown hooks.
注册新的虚拟机 关闭挂钩.
Registers a new virtual-machine shutdown hook.
Java虚拟机在 对两种事件的响应:
The Java virtual machine shuts down in response to two kinds of events:
-
当最后一个非守护程序线程退出或调用exit(等效于System.exit)方法时,程序会正常退出,或者
The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
响应于用户中断(例如键入^ C)或系统范围的事件(例如用户注销或系统关闭)而终止虚拟机.
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 (关闭)钩子,没有想到.在kill -15
上,它确实每次都运行关闭钩子.
I tried the following test program on OSX 10.6.3 and on kill -9
it did NOT run the shutdown hook, didn't think it would. On a kill -15
it DOES run the shutdown hook every time.
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);
}
}
}
这是编写您自己的信号处理程序在Java中不是shutdown挂钩. 警告 com.sun.misc
软件包和未受支持,并且可以随时更改或取消,并且可能仅存在于Sun JVM中.
This is the documented way to write your own signal handlers that aren't shutdown hooks in Java. Be warned that the com.sun.misc
packages and are un-supported and may be changed or go away at any time and probably only exist in the Sun JVM.
这篇关于用Java捕获SIGINT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!