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
nin 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 systemandman waitcarefully, and you’ll understand.