popen函数可以获取比std::system函数更详细的程序输出。只是正常调用 popen 只能获取 stdout 的输出,而 stderr 的输出被忽略。
因此可以简单用sh -c '{}' 2>&1封装一下命令,将 stderr 重定向到 stdout ,再执行 popen 获取所有的输出:
std::pair<int, std::string> exec(std::string command, bool with_stderr = true)
{
    char buffer[1280];
    std::string result = "";
    if (with_stderr) {
        command = fmt::format("sh -c '{}' 2>&1", command);
    }
    FILE* pipe = popen(command.c_str(), "r");
    if (!pipe) {
        return {errno, fmt::format("popen failed: {}", strerror(errno))};
    }
    // read till end of process:
    while (!feof(pipe)) {
        // use buffer to read and add to result
        if (fgets(buffer, sizeof(buffer), pipe) != NULL)
            result += buffer;
    }
    pclose(pipe);
    return {0, result};
}
使用中要注意,命令中不能包含单引号。另外过于复杂的命令也可能有问题。
Q. E. D.