linux 获取popen执行命令的返回值
时间: 2023-08-12 22:57:42 浏览: 107
在Linux中,你可以使用`pclose`函数来获取`popen`执行命令的返回值。`pclose`函数会等待命令执行完毕,并返回命令的退出状态。
下面是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
char result[1024];
// 执行命令并读取输出
fp = popen("ls -l", "r");
if (fp == NULL) {
printf("Failed to run command\n");
return 1;
}
// 读取命令输出
while (fgets(result, sizeof(result), fp) != NULL) {
printf("%s", result);
}
// 获取命令的返回值
int status = pclose(fp);
if (status == -1) {
printf("Failed to get command exit status\n");
return 1;
}
if (WIFEXITED(status)) {
int exitStatus = WEXITSTATUS(status);
printf("Command exited with status: %d\n", exitStatus);
} else if (WIFSIGNALED(status)) {
int signal = WTERMSIG(status);
printf("Command terminated by signal: %d\n", signal);
}
return 0;
}
```
在上面的示例中,我们使用`popen`执行了一个`ls -l`的命令,并通过`fgets`函数读取了输出结果。然后,我们使用`pclose`获取命令的返回值,并通过`WIFEXITED`和`WEXITSTATUS`宏判断命令是正常退出还是被信号终止,并打印相应的信息。
需要注意的是,`pclose`返回的状态值包含了命令的退出状态,可以使用`WEXITSTATUS`宏获取真正的退出状态值。另外,还可以使用`WIFSIGNALED`和`WTERMSIG`宏来获取命令被哪个信号终止(如果是这种情况)。
请根据你的实际需求修改命令和输出结果的处理方式。