Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should my program's exit code be if I caught a signal?

I think I may have been doing this wrong for a while, because we just switched to systemd and it's considering my cleanly-killed process to have ended unsuccessfully.

Basically I listen for SIGHUP, SIGINT and SIGTERM and then (by passing the signal code back up to main) cleanly e.g. return 128+SIGHUP.

I expected this to be used to populate $?, but now I think I understand that the shell is responsible for giving $? such a value, and then only if the signal was unhandled. So even if the process exited ultimately due a signal, because the signal was handled, $? will end up being 0 and all evidence that a signal had anything to do with the exiting will be lost. Is that right?

When handling SIGHUP and cleanly exiting, should I return EXIT_SUCCESS from main?

like image 908
Lightness Races in Orbit Avatar asked Sep 01 '16 10:09

Lightness Races in Orbit


1 Answers

The convention of returning 128 + <signal number> is promoted by the Advanced Bash Scripting Guide among others (https://stackoverflow.com/a/1535733/567292), but is only for the case when your program fails as a result of receiving the signal.

If your program receives the signal, does not handle it, and is terminated as a result, the exit status (as provided e.g. by wait) will be similar but instead of bit 7 set will have a higher bit set to indicate WIFSIGNALED as opposed to WIFEXITED. If you are running in a shell, this is then translated by the shell to give an exit status ($?) in the range 128-255 (i.e., with bit 7 set), so as far as a shell script is concerned, a program returning 128+n is indistinguishable from a program terminating because a signal was unhandled:

[...] When reporting the exit status with the special parameter '?', the shell shall report the full eight bits of exit status available. The exit status of a command that terminated because it received a signal shall be reported as greater than 128.

If your program receives a signal then successfully exits, this is considered a successful termination, so your program should return EXIT_SUCCESS.

like image 52
ecatmur Avatar answered Sep 22 '22 12:09

ecatmur