views:

135

answers:

1

Hi all,

I want it so when my users start my program from the command line and then kill the process (ctrl+c, for example) the program will shutdown gracefully by closing all its connections. Is this even possible? I can't just have it call a method upon closing like a GUI can? This program has no GUI.

Please let me know.

Thanks, jbu

+6  A: 

Here is a pretty good guide to signal handling in Java. It covers shutdown and termination cases as well, including Ctrl-C.

The specific call you want is in the Runtime, addShutdownHook.

There are still specific cases that you cannot handle... there is usually some way for the OS to just outright kill the application without giving it a chance to save itself. You can't cover every case through this mechanism. To quote the JavaDoc

In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly. This occurs when the virtual machine is terminated externally, for example with the SIGKILL signal on Unix or the TerminateProcess call on Microsoft Windows. The virtual machine may also abort if a native method goes awry by, for example, corrupting internal data structures or attempting to access nonexistent memory. If the virtual machine aborts then no guarantee can be made about whether or not any shutdown hooks will be run.

Chris Arguin
It's probably obvious, but nonetheless I feel obligated to point out that if the process is force-killed (SIGKILL in Unix, `taskkill /f` in Windows), there's no way it can detect the fact or do anything. It just dies right there and then, unless it's in uninterruptible sleep (and if it is, it'll die immediately once it leaves that state).
Pavel Minaev
Good point; I've updated to include that.
Chris Arguin
Of course, its a feature like we have 'shutdown abort' in Oracle. One can't help, and should not, because overcoming this is similar to revoking a user right, IMO.
Adeel Ansari