linux c++ 调用shell命令,保存执行结果 示例

下面的代码用于在c++函数里面调用shell,并且执行命令,取回命令执行结果。

#include <cstdio>
#include <string>
#include <string.h>
#include <iostream>

int main()
{
    const int SIZE = 64;
    const int MAX_RESPONSE_SIZE = 65535;
    char charBuff[SIZE];
    int bytesRead = 0;
    int closeResult;
    std::string result_;
    std::string cmd_ = "ls -al"; // 要执行的命令

    if (system(nullptr) == 0) // 查看shell是否可用
    {
        std::cout << "shell not available" << std::endl;
        return 1;
    }

    auto cmdOut = popen(cmd_.c_str(), "r"); // 执行命令
    if (cmdOut == nullptr)
    {
        std::cout << "popen error" << std::endl;
        return 1;
    }

    while (fgets(charBuff, SIZE, cmdOut) != nullptr) // 循环读取命令执行结果
    {
        if (bytesRead + strlen(charBuff) >= MAX_RESPONSE_SIZE)
        {
            result_.append(charBuff, MAX_RESPONSE_SIZE - bytesRead);
            break;
        }
        else
        {
            result_.append(charBuff);
        }

        bytesRead += strlen(charBuff);
    }

    closeResult = pclose(cmdOut); // 关闭

    std::cout << "bytesRead=" << bytesRead << std::endl;
    std::cout << "closeResult=" << closeResult << std::endl;
    std::cout << "WEXITSTATUS(closeResult)=" << WEXITSTATUS(closeResult) << std::endl;
    std::cout << "result=" << result_ << std::endl;

    return 0;
}

结果如下

[root@test shell]# ./main
bytesRead=246
closeResult=0
WEXITSTATUS(closeResult)=0
result=total 20
drwxr-xr-x 3 root root    49 Dec  5 08:00 .
drwxr-xr-x 5 root root    92 Dec  5 07:40 ..
-rwxr-xr-x 1 root root 14416 Dec  5 08:00 main
-rw-r--r-- 1 root root  1205 Dec  5 08:00 main.cpp
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值