c - 在c中使用时系统命令的返回值是什么

标签 c shell

我正在使用 linux 系统命令来终止 c 文件中的一些进程。我只想知道可能的不同返回值。我在网上搜索时不清楚。我在 c 中使用的以下命令。

ret = system("pkill raj");
  • 假设如果没有运行 raj 的进程,返回值是什么?
  • 假设如果命令 pkill raj 失败,返回值是什么?
  • 假设有一些名为 raj 的进程。执行此操作后,返回值将是什么。

最佳答案

来自手册页:

The value returned is -1 on error (e.g. fork(2) failed), and the return status of the command otherwise. This latter return status is in the format specified in wait(2). Thus, the exit code of the command will be WEXITSTATUS(status). In case /bin/sh could not be executed, the exit status will be that of a command that does exit(127).

因此您需要检查 WEXITSTATUS(ret) 以获得 pkill 命令的返回值。

代码示例:

#include <stdio.h>
#include <stdlib.h>


int main(int argc, char **argv)
{
        int status;
        if(( status = system("kill -9 13043")) != -1){
                fprintf(stdout, "kill command exit status: %d\n", WEXITSTATUS(status));
        }

        return 0;
}

关于c - 在c中使用时系统命令的返回值是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8149772/

相关文章:

python - 用合理的语言编写 UNIX shell?

linux - 历史扩展在脚本中不起作用

c++ - 在 C 中使用 CoGetClassObject() - 访问 COM 对象接口(interface)

将 TSV 文件中的内容转换为多维数组

c - 适用于 Mac OS X 的 16 位实模式 C 编译器

bash - 可以通过CLI在Linux中使音频静音的脚本有效,但需要帮助

C 文件顶部新行

c - 忽略scanf的返回值

bash - 如何在 bash 脚本中连接变量和字符串

python - 禁用 argparse 参数的正则表达式