我有一个 C
代码可以在 shell 上执行一些命令。代码是这样的:
int main(){
int x=0;
x=system("some command");
printf("Exit Status:%d\n",x);
return 0;
}
这里的问题是在失败时我得到了一些不同于 x 的退出值的值。
假设如果我们在 bash
上执行 xyz
,它退出时状态为 127,因为找不到命令,或者如果命令存在但失败则为 1。如何将此 127 或 1 放入我的 C
代码中。
最佳答案
使用(至少在 Linux 上)与 waitpid(2) 相关的宏
int x = system("some command");
if (x==0)
printf("command succeeded\n");
else if (WIFSIGNALED(x))
printf("command terminated with signal %d\n", WTERMSIG(x));
else if (WIFEXITED(x))
printf("command exited %d\n", WEXITSTATUS(x));
等等。阅读更多关于 system(3) 的信息.当心code injection当传递给 system
一些运行时生成的字符串时。
关于c - 如何在 C 中获取 shell 命令 [通过 system() 运行] 的退出状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33810371/