How to handle a SIGTERM

前端 未结 3 651
一生所求
一生所求 2020-11-29 00:06

Is there a way in Java to handle a received SIGTERM?

3条回答
  •  天命终不由人
    2020-11-29 00:56

    You could add a shutdown hook to do any cleanup.

    Like this:

    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.
        }   
    }
    

    Then run it:

    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
    

提交回复
热议问题