I'm testing this tiny program under Linux:
// foo.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
int n = system(argv[1]);
printf("%d\n", n);
return n;
}
No matter what is fed into the command-line, an echo $?
always prints 0, e.g.:
$ ./foo anything
sh: anything: not found
32512
$ echo $?
0
My question is: Why doesn't $?
take the same value as n
? I've also tested the program under Win32, and echo %errorlevel%
gives the same value as n
. Thanks!
If you print n
in octal or hex, you'll discover that the low byte of it is always 0.
If you return WEXITSTATUS(n);
, your program will exit with the status you are expecting.
Read man system
and man wait
carefully, and you'll understand.
Only lower 8 bits of the return value are recognized as the exit status, because the exit status is calculated by WEXITSTATUS
macro, see SUSv4
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