Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is $? always 0 after system() is called?

Tags:

c

linux

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!

like image 231
wdscxsj Avatar asked Dec 23 '11 07:12

wdscxsj


2 Answers

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.

like image 140
Employed Russian Avatar answered Oct 11 '22 14:10

Employed Russian


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

like image 2
wRAR Avatar answered Oct 11 '22 16:10

wRAR