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?

3
  • 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, 2016 at 17:04
  • a java program that is running as a daemon started with upstart is running the shell script process
    – jgr208
    May 16, 2016 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, 2016 at 18:11

1 Answer 1

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.

3
  • 1
    Note that this is only reliable for signal 9 which can't be trapped. Other signals can be trapped by the program which can then exit with any value.
    – GnP
    May 20, 2016 at 20:06
  • yes, as gnp told, the kill -9 cannot be traped
    – c4f4t0r
    May 23, 2016 at 17:42
  • Do you have any sources?
    – Twifty
    May 30, 2018 at 7:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.