0

If I press CTRL + C at caffeinate -i I have a non 0 exit status.

enter image description here

My terminal prompt shows me with red x that the previous command had a not 0 exist status. Why is that?

1
  • 4
    The simple answer is "because caffeinate is programmed to return a non-zero exit code if interrupted". Which practical problem are you trying to solve here?
    – nohillside
    Commented Jul 22, 2022 at 5:32

2 Answers 2

1

Because 0 indicates normal exit with a success status. Any other way to exit (with an error report, or an abnormal exit) causes a nonzero status.

There are two ways a program can end: either because it explicitly asked to exit (with the exit system call or equivalent), or because it was killed by a signal. If the program exits, it indicates its exit status as an argument to the exit system call, which is conventionally 0 for success and a number between 1 and 255 for errors. (What happens with higher values, or whether even higher values are possible, depends on the operating system, so very few programs even try.) If the program is killed by a signal, there is no exit status from the program (it didn't get a chance to set one), but instead the exit status indicates which signal killed the program.

The program's exit status is conveyed to the program's parent process via the wait system call (or equivalent). It encodes both the explicit exit status for normal termination (if the program called exit), and the signal number for abnormal termination (if the program was killed by a signal). In the shell, the status information, available in the special variable $?, is blended somewhat: it's the program's exit status for a normal termination, and the signal number plus 128 for abnormal termination. All signal numbers are in the range [1, 127], so $? is 0 for success, (normally) 1 to 127 for a normal exit indicating failure, and 129 to 255 for a signal.

Pressing Ctrl+C sends the signal SIGINT. If the program dies from it, its shell exit status is 130 (128 + SIGINT, and SIGINT = 2 on macOS).

Some programs catch signals and run some cleanup code so that events like Ctrl+C cause a clean shutdown. Normally, once they've finished cleaning up, they disable the signal handler and re-raise the signal (rather than calling exit), so that the reason for termination is reflected in their exit status.

1
  • Great answer... amazing that it's gotten no upvotes in a year.
    – Seamus
    Commented Nov 14, 2023 at 22:31
0

The source is at opensource.apple.com. Basically caffeinate -i ends up in a call to dispatch_main() which never returns (so it only can be interrupted).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .