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

如果在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");
}

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值