您的位置:首页 > 运维架构 > Shell

C程序中如何获取shell命令执行结果和返回值

2016-10-24 18:55 681 查看
如果在C程序中调用了shell命令,那么往往希望得到输出结果以及命令执行的返回布尔值。在这里分为两步来处理:

1.使用 popenpclose 来执行shell命令;

2.使用‘echo $?’来获取上一条指令执行状态,如果为0那么标识成功执行,否则标识执行出错;

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

int main(void)
{
FILE *stream = NULL;
char buf[1024];
int ret;

memset(buf, 0, sizeof(buf));
if ((stream = popen("ifconfig", "r")) == NULL) {
fprintf(stderr, "%s", strerror(errno));
return -1;
}
/* output the message */
while (fgets(buf, sizeof(buf), stream) != NULL) {
printf("%s", buf);
}

if ((stream = popen("echo $?", "r")) == NULL) {
fprintf(stderr, "%s", strerror(errno));
return -1;
}
/* output the message */
while (fgets(buf, sizeof(buf), stream) != NULL) {
printf("%s", buf);
}
ret = atoi(buf);
if (ret)
printf("command excutes succeed!\n");
else
printf("command excutes fail!\n");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: