The exit status from the process is encoded in 16 bits. The high-order 8 bits contain the return value from main()
or the value passed to exit()
(or one of its relatives); the low-order 8 bits contain the signal that killed the process and a flag indicating that a core dump was created. The low order bits are zero if the process exited normally. The return value from wait()
is the PID of the dead process.
Use code similar to this to print out the information in a semi-legible format:
int corpse;
int status;
while ((corpse = wait(&status)) > 0)
printf("PID %5d exited with status 0x%.4X\n", corpse, status);
If your program has return 3;
at the end of main()
, then the value reported via the status pointer to wait()
will be 0x0300
(768 = 3 * 256). If your program calls exit(100);
, the value returned by wait()
will be 0x6400 (100 = 6 * 16 + 4). If your program is killed by an interrupt (SIGINT, 2), the value returned by wait()
will be 0x0002. (Technically, the actual values are system-dependent, but this is historically accurate and I know of no system where this is not what happens.)
See also ExitCodes bigger than 255 — Possible?.
POSIX defines the <sys/wait.h>
header with a bunch of relevant macros, such as:
WIFEXITED
WEXITSTATUS
WIFSIGNALED
WTERMSIG
WIFSTOPPED
WSTOPSIG
And implementations often define a macro to detect core dumps — usually WCOREDUMP
.
See also the POSIX specification for wait()
(which also specifies waitpid()
).