Reese
Reese

Reputation: 173

Shutdown hook from UNIX

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.");
    }   
}

Upvotes: 5

Views: 4194

Answers (3)

i30817
i30817

Reputation: 1388

This has nothing to do with the signals the JVM is trapping/receiving but everything to do with the terrible shutdown process of Gnome, which apparently needs to be cooperative not to absolutely shit the bed (and the jdk doesn't have the api for this). If you want to see a even worse consequence of this, try to run:

dbus-monitor --profile --session type='method_call',interface='org.gnome.SessionManager'

on a shell, and logout or restart: it will crash gnome-shell and hang the computer until you login on a TTY and order a restart. Maybe kdbus will fix this on this case, maybe not. The only thing i know is that shutdownhooks on a java application that is using AWT (not command line) will NEVER run its shutdownhooks on GNOME3. Actually, the VM will always exit with non-zero code (failure) presumably from native code. At least it doesn't hang, although this makes shutdown hooks quite useless (i've been trying to make a workaround by using dbus-monitor, but as you can see from the example i gave, it's a bit too dangerous too).

Upvotes: 0

Ingo Kegel
Ingo Kegel

Reputation: 47985

kill -9 <pid> sends a KILL signal. This signal cannot be intercepted by the program.

If you call kill <pid>, the TERM signal (15) wil be sent. In that case, the JVM will catch the signal and the shutdown hooks will be executed.

Upvotes: 4

anubhava
anubhava

Reputation: 785128

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);
   }
});

Upvotes: 6

Related Questions