15

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?

terdon
  • 234,489
  • 66
  • 447
  • 667
jgr208
  • 888
  • 14
  • 35
  • 4
    What is running the shell script? That process should have access to the `status` of the child process via `wait(2)` or something. – thrig May 16 '16 at 17:04
  • a java program that is running as a daemon started with upstart is running the shell script process – jgr208 May 16 '16 at 17:09
  • 1
    You could strace the program and look for a line that says "killed by SIGKILL" or do some auditd work with `-a entry,always -F arch=b64 -S kill -k kill_signals` – Bratchley May 16 '16 at 18:11

1 Answers1

21

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.

Lucas
  • 2,805
  • 1
  • 14
  • 24