c++ 执行系统命令system 、popen

一、系统命令system

1、示例:

#include <cstdlib> // 必须包含这个头文件来使用system()

int main() {
    system("sleep 10"); // 塞执行
    return 0;
}
  1. 程序会等待10秒后,执行完成
  2. 使用system("sleep 10 &");可以实现非阻塞执行

2、示例: 注意若用了分号;&只对前面指令有效

#include <cstdlib> // 必须包含这个头文件来使用system()

int main() {
    system("sleep 10; ls &"); // 非阻塞执行
    return 0;
}

3、示例

#include <cstdlib> // 必须包含这个头文件来使用system()

int main() {
    system("sleep 10 && ls &"); // 非阻塞执行
    return 0;
}

二、系统命令获取返回值

popen示例一:保留’\n’

#include <iostream>
#include <unistd.h>
#include <sys/types.h>

std::string execCmd(const char* cmd) {
    FILE *pp = popen(cmd, "r");
    char tmp[1024];
    std::string result;
    while (fgets(tmp, sizeof(tmp), pp) != NULL)
        result += tmp;
    pclose(pp);
    return result;
}

int main() {
    for (int i = 0; i < 10; ++i) {
        std::string output = execCmd("ls");
        std::cout << output;
    }
    return 0;
}

示例二:

#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <cstring>
std::string execCmd(const char* cmd) {
    FILE *pp = popen(cmd, "r");
    char tmp[1024];
    std::string result;
    while (fgets(tmp, sizeof(tmp), pp) != NULL) {
        // 去除换行符
        size_t pos = strlen(tmp);
        if (pos > 0 && tmp[pos - 1] == '\n') {
            tmp[pos - 1] = '\0';
        }
        result += tmp;
    }
    pclose(pp);
    return result;
}

int main() {
    for (int i = 0; i < 10; ++i) {
        std::string output = execCmd("pwd");
        std::cout << output;
    }
    return 0;
}

示例三

#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>

std::string exec(const char* cmd) {
    std::array<char, 128> buffer;
    std::string result;
    std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);

    if (!pipe) {
        throw std::runtime_error("popen() failed!");
    }

    while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
        result += buffer.data();
    }

    return result;
}

int main() {
    try {
        std::string command = "cat 22/ZX_FourdDataStruct.h";
        std::string output = exec(command.c_str());
        std::cout << "Output:\n" << output << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值