Is there any way to tell if a shell script was killed with signal 9

I have a bash script (called from a java program) that keeps getting killed. I always catch the signal 15 with trap but then some other signal comes along that I suspect is signal 9 but am in basically blind as to if it is really signal 9.

I know you can’t trap signal 9, so is there any other way I can tell if signal 9 is killing my shell script?

Answer

The exit status of a killed command should be the signal number plus 128. So you can use the exit status to find out which signal killed you process.

I tested it like this on Linux in the shell:

print_exit_status_for_signal () {
  (
    sleep 1000
    echo Exit staus $? = signal $(( $? - 128 ))
  ) &
  sleep 1
  killall "${1:+-$1}" sleep
}
print_exit_status_for_signal
print_exit_status_for_signal 15
print_exit_status_for_signal 9
print_exit_status_for_signal KILL
print_exit_status_for_signal TERM

EDIT: Note that a program can decide to exit with any¹ value (so you have to decide how far you trust the exit status to be the effect of a signal):

for i in $(seq 256); do
  sh -c "exit $i"
  echo Program exited with $?
done

Footnote 1: On my systems exit codes are represented as unsigned 8-bit numbers so they wrap at 256=0.

Leave a Reply

Your email address will not be published. Required fields are marked *