6

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?

Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989

2 Answers2

5

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.

Community
  • 1
  • 1
ecatmur
  • 137,771
  • 23
  • 263
  • 343
2

Return Codes are usually what you specify them. When you want to include signal to exit codes, you have to make sure they still stay unique.

If you don't need the signal in the exit code there seems to be no reason to include them though.

Whether to return EXIT_SUCCESS or EXIT_FAILURE is up to you/your program whether the termination counts as success or failure.

Hayt
  • 4,748
  • 24
  • 34