如何处理 SIGTERM

2022-08-31 12:01:33

在Java中,有没有办法处理收到的SIGTERM?


答案 1

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


答案 2

您可以添加一个关机挂钩来执行任何清理操作。

喜欢这个:

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

推荐