3

我正在运行 MacOS 并希望执行“ps aux”命令并通过我的应用程序获取其输出。我编写了一个使用 popen 函数执行命令的方法:

std::string exec(const char* cmd) {

    char buffer[128];
    std::string result = "";

    FILE* pipe = popen(cmd, "r");
    if (!pipe) throw std::runtime_error("popen() failed!2");
    try {
        while (!feof(pipe)) {
            if (fgets(buffer, 128, pipe) != NULL)
                result += buffer;
        }
    } catch (...) {
        pclose(pipe);

        throw;
    }
    pclose(pipe);


    return result;
}

我有一个不断运行 exec("ps aux") 函数的循环。问题是来自 popen 的管道没有关闭,我已经使用终端中的“lsof”命令进行了检查。大约 20 秒后,应用程序打开了大约 300 个文件描述符,这阻止了应用程序从循环中打开更多管道(运行“ps aux”命令)。

我发现,exec 函数适用于其他命令(管道正确关闭),例如“netstat”,因此它必须是“ps aux”命令中阻止管道关闭的东西。

我已经搜索了很多关于该问题的信息,但没有找到任何解决方案。有人可以指出我正确的方向吗?

谢谢!

4

1 回答 1

0

我看不出你的代码有什么特别的问题。对于这些事情,我使用带有 a 的自定义删除器std::unique_ptr来确保文件在所有可能的出口处关闭。

while(eof(...))另请注意,出于某些原因,不建议循环使用。一种是在发生错误时未设置 eof。更多信息在这里

// RAII piped FILE*

// custom deleter for unique_ptr
struct piped_file_closer
{
    void operator()(std::FILE* fp) const { pclose(fp); }
};

// custom unique_ptr for piped FILE*
using unique_PIPE_handle = std::unique_ptr<std::FILE, piped_file_closer>;

//
unique_PIPE_handle open_piped_command(std::string const& cmd, char const* mode)
{
    auto p = popen(cmd.c_str(), mode);

    if(!p)
        throw std::runtime_error(std::strerror(errno));

    return unique_PIPE_handle{p};
}

// exception safe piped reading
std::string piped_read(std::string const& cmd)
{
    std::string output;

    if(auto pipe = open_piped_command(cmd, "r"))
    {
        char buf[512];
        while(auto len = std::fread(buf, sizeof(char), sizeof(buf), pipe.get()))
            output.append(buf, len);

        if(std::ferror(pipe.get()))
            throw std::runtime_error("error reading from pipe");
    }

    return output;
}

在我的系统上调用auto output = piped_read("ps aux");数百次不会产生此代码的错误。

于 2018-02-20T18:49:33.600 回答