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?
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.
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.
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.
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.
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.
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