5

C++ 中执行并获取命令行输出(包括 stderr)

 3 years ago
source link: https://zhiqiang.org/coding/cpp-exec-and-capture-cmd-output.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

C++ 中执行并获取命令行输出(包括 stderr)

作者: 张志强

, 发表于 2021-03-09

, 共 867 字 , 共阅读 65 次

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.

avatar-0.jpg

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK