在C语言中如何获取shell命令的执行退出状态码?
代码错误点与修正方案
第一版fork+execl实现的错误
execl第一个参数错误:你传入的是C源文件路径,并非可执行程序路径。要调用shell执行命令,第一个参数应填写shell的可执行路径/bin/sh- 缺少shell的
-c参数:直接给shell传命令字符串时,必须加-c参数,否则shell会将后续参数识别为脚本文件名而非执行命令 - 命令书写错误:
cat/proc/1/mem中间缺少空格,属于无效命令,正确写法为cat /proc/1/mem - 未处理
execl执行失败的情况:如果execl调用失败,子进程会继续执行父进程的后续代码,需要在execl后加退出逻辑避免异常 - 存在笔误:变量名
exit_stauts拼写错误,输出字符串Exist应为Exit(不影响核心功能)
第二版system实现的错误
- 逻辑判断顺序错误:
system返回值不是直接等于命令退出码,需要先通过WIFEXITED判断是否为正常退出,再用WEXITSTATUS提取退出码。你提前判断x==0会漏掉所有正常退出但返回非0状态码的情况 - 同样存在命令书写错误:
cat/proc/1/mem缺少空格
修正后的代码示例
fork+execl版本
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/wait.h> #include <sys/types.h> int main() { pid_t pid = fork(); if(pid == 0) { // 第一个参数是shell可执行路径,加-c参数后接要执行的命令 execl("/bin/sh", "/bin/sh", "-c", "cat /proc/1/mem", NULL); // execl调用失败才会走到这里,直接退出子进程 perror("execl执行失败"); exit(EXIT_FAILURE); } int status; waitpid(pid, &status, 0); if(WIFEXITED(status)) { int exit_status = WEXITSTATUS(status); printf("Exit status is %d\n", exit_status); } else if(WIFSIGNALED(status)) { printf("命令被信号终止,信号编号:%d\n", WTERMSIG(status)); } return 0; }
system版本
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/wait.h> int main() { int status = system("cat /proc/1/mem"); if(WIFEXITED(status)) { int exit_code = WEXITSTATUS(status); if(exit_code == 0) { printf("命令执行成功,exit status is %d\n", exit_code); } else { printf("命令执行结束,exit status is %d\n", exit_code); } } else if (WIFSIGNALED(status)) { printf("命令被信号终止,信号编号:%d\n", WTERMSIG(status)); } return 0; }
内容的提问来源于stack exchange,提问作者Rares Amza
相关产品推荐
相关产品推荐

