Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit Codes from system() not as expected

Tags:

c

linux

freebsd

The system() function seems to be returning 128 times the exit code I get from the process it's evoking.

From the man page:

RETURN VALUE The value returned is -1 on error (e.g., fork(2) failed), and the return status of the command other‐ wise.

Here is what I've got.

$ ls tinker.c
tinker.c
$ echo $?
0
$ ls notexisting
ls: cannot access notexisting: No such file or directory
$ echo $?
2
$ cat tinker.c
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    printf("%d\n", system("ls tinker.c"));
    printf("%d\n", system("ls notexisting"));
    return 0;
}
$ gcc tinker.c -o tinker
$ ./tinker 
tinker.c
0
ls: cannot access notexisting: No such file or directory
512

The first call indicates that I'm not getting failures but the return codes look nothing like what I'm reading from the man page. What'm I doing wrong?

like image 700
Ishpeck Avatar asked Nov 18 '12 16:11

Ishpeck


People also ask

What does exit code 255 mean?

While trying to use SSH, you may get a response indicating permission is denied. Or if you get an error with a code of 255, it means there's a problem with your SSH connection. The command failed with the exit code: 255.

How does python handle exit codes?

This can be achieved by calling the sys. exit() function and passing the exit code as an argument. The sys. exit() function will raise a SystemExit exception in the current process, which will terminate the process.

What is the range of exit codes for an unsuccessful command execution?

After a script terminates, a $? from the command-line gives the exit status of the script, that is, the last command executed in the script, which is, by convention, 0 on success or an integer in the range 1 - 255 on error.


2 Answers

Your citation of the system man page misses the relevant part:

... This latter return status is in the format specified in wait(2). Thus, the exit code of the command will be WEXITSTATUS(status).

You need to right shift the return value by 8 (at least on Linux), to get the commands exit code.

The portable approach is to just use the macro itself.

like image 127
alk Avatar answered Oct 06 '22 21:10

alk


From POSIX system(3):

If command is not a null pointer, system() shall return the termination status of the command language interpreter in the format specified by waitpid().

To get the return code, you need to use the WEXITSTATUS macro.

like image 44
Mat Avatar answered Oct 06 '22 20:10

Mat