如何处理SIGTERM

时间:2010-06-04 14:53:41

标签: java exit sigterm

Java中是否有办法处理收到的SIGTERM?

3 个答案:

答案 0 :(得分:55)

是的,您可以使用Runtime.addShutdownHook()注册关机挂钩。

答案 1 :(得分:36)

您可以添加shutdown hook进行任何清理。

像这样:

public class myjava{
    public static void main(String[] args){
        Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
            public void run() {
                System.out.println("Inside Add Shutdown Hook");
            }   
        }); 

        System.out.println("Shut Down Hook Attached.");

        System.out.println(5/0);     //Operating system sends SIGFPE to the JVM
                                     //the JVM catches it and constructs a 
                                     //ArithmeticException class, and since you 
                                     //don't catch this with a try/catch, dumps
                                     //it to screen and terminates.  The shutdown
                                     //hook is triggered, doing final cleanup.
    }   
}

然后运行它:

el@apollo:~$ javac myjava.java
el@apollo:~$ java myjava 
Shut Down Hook Attached.
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at myjava.main(myjava.java:11)
Inside Add Shutdown Hook

答案 2 :(得分:5)

在Java中处理信号的另一种方法是通过sun.misc.signal包。有关如何使用它的信息,请参阅http://www.ibm.com/developerworks/java/library/i-signalhandling/

注意: sun。*包中的功能也意味着它可能在所有操作系统中都不可移植/表现相同。但你可能想尝试一下。