djechlin
djechlin

Reputation: 60768

Java - programmatically set exit code from SIGTERM

Situation: I have a keep-alive shell script that restarts an application whenever it shuts down. However I do not want it to do this if the application was closed via a SIGTERM or SIGINT (kill, Ctrl+C, etc.) i.e. a shutdown hook. However I have no way of setting the exit code, hence communicating to the keep-alive script, when exiting from a shutdown hook as calling exit is illegal.

From Javadocs for exit:

If this method is invoked after the virtual machine has begun its shutdown sequence then if shutdown hooks are being run this method will block indefinitely. If shutdown hooks have already been run and on-exit finalization has been enabled then this method halts the virtual machine with the given status code if the status is nonzero; otherwise, it blocks indefinitely.

Is this possible?

Upvotes: 4

Views: 1996

Answers (3)

Evgeniy Berezovsky
Evgeniy Berezovsky

Reputation: 19228

Here's what I do:

Runtime.getRuntime().halt(0);

Note that this will exit the program immediately, so you need to do it after the last shutdown hook has finished.

Upvotes: 0

fge
fge

Reputation: 121710

Grab the PID of the process in a variable and use the wait builtin: if the process has been terminated by a signal, the return code of wait will be 128 + the signal number.

#
# Note: output from shell trimmed
#
# Launch cat in the background, capture the PID
$ cat & PIDTOCHECK=$!
$ echo $PIDTOCHECK
27764
#
# Call wait a first time: the program is halted waiting for input (SIGTTIN)
#
$ wait $PIDTOCHECK ; echo $?
149
#
# Now kill cat, and call wait again
#
$ kill %1
$ wait $PIDTOCHECK ; echo $?
143

Upvotes: 0

NPE
NPE

Reputation: 500357

If the process has been killed by a signal, the $? variable will be set to 128 + signal:

bash$ sleep 3;echo $?
0

bash$ sleep 3;echo $?
^C
130

Here, 130 is 128 + SIGINT.

Upvotes: 4

Related Questions