📜  如何在 C++ 代码示例中执行命令并获取命令的返回码 stdout 和 stderr

📅  最后修改于: 2022-03-11 14:44:54.129000             🧑  作者: Mango

代码示例1
std::string exec(const char* cmd) {
    std::array buffer;
    std::string result;

    auto pipe = popen(cmd, "r"); // get rid of shared_ptr

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

    while (!feof(pipe)) {
        if (fgets(buffer.data(), 128, pipe) != nullptr)
            result += buffer.data();
    }

    auto rc = pclose(pipe);

    if (rc == EXIT_SUCCESS) { // == 0

    } else if (rc == EXIT_FAILURE) {  // EXIT_FAILURE is not used by all programs, maybe needs some adaptation.

    }
    return result;
}