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
?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With