Exit Codes from system() not as expected

廉价感情. 提交于 2020-07-03 06:53:19

问题


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?


回答1:


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.




回答2:


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.




回答3:


0 and 512 are the termination status of the command.

If the command executes successfully, it returns a 0 value, otherwise, it returns a non-zero value. And this non-zero value is various in different OSs. In my mac os, the return value of the second system command is 256.

You can also get answer from this question `ls` exit status.



来源:https://stackoverflow.com/questions/13441872/exit-codes-from-system-not-as-expected

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!