Shutdown hook from UNIX

java, shutdown-hook, unix

Solution

You can use code like this on Unix to trap SIGINT (#2) signal:

Signal.handle(new Signal("INT"), new SignalHandler() {
      public void handle(Signal sig) {
      // Forced exit
      System.exit(1);
   }
});

Problem

I am trying to get my Java program to exit gracefully on my unix server. I have a jar file, which I start through a cron job in the morning. Then in the evening, when I want to shut it down, I have a cron job which calls a script that finds the PID and calls `kill -9 <PID>`. However, it doesn't seem that my shutdown hook is activated when I terminate this way. I also tried `kill <PID>` (no -9) and I get the same problem. How can I make sure the shutdown hook gets called? Alternatively, perhaps there is a better way to kill my process daily. ``` class ShutdownHook { ShutdownHook() {} public void attachShutDownHook() { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.out.println("Shut down hook activating"); } }); System.out.println("Shut Down Hook Attached."); } } ```

Original source