Foundations: The Machine Model

the exit status

When a program finishes, it leaves behind one small parting message: a single number telling whoever launched it whether things went well. That number is the exit status. Think of it as a worker handing back a one-word report after a job - 'done' or 'failed' - so the boss (often a shell script) knows what to do next without reading the whole output.

By long-standing convention, an exit status of 0 means success and any non-zero value means some kind of failure, with different numbers often standing for different problems. In C, the value you return from main becomes the exit status (return 0; reports success); a program can also end early by calling exit(1) with a status. The operating system records this small integer when the process ends, and the parent that started the program - a shell, a script, another program - can read it to decide whether to continue, retry, or stop.

Why it matters: the exit status is how programs talk to each other about success and failure, and it is the backbone of shell scripting and automation. A line like 'make && ./run-tests' only runs the tests if make's exit status was 0. Getting this right - returning 0 only when you truly succeeded, and a clear non-zero code on failure - is part of being a good citizen on a Unix system. The convention is the reverse of everyday intuition, where you might expect 1 to mean 'yes/good'; here 0 is the all-clear and non-zero is trouble.

After running a command, the shell stores its exit status in $?: '$ ./hello; echo $?' prints 0 because hello did return 0;. If a program crashes or returns 1, you would see a non-zero number, and 'cmd1 && cmd2' would skip cmd2.

0 means success; the shell reads $? to know whether the last command worked.

0 = success is the opposite of the usual 'true = 1' habit, and it trips people up. Also, only the low 8 bits of the status are kept on Unix, so returning 256 wraps to 0 and looks like success - keep exit codes in the 0-255 range.

Also called
exit codereturn codeexit valuestatus code離開碼回傳碼