如何使用C ++ libboost运行进程并获取其输出?

时间:2018-09-05 14:41:27

标签: c++ boost c++17

我正在尝试运行外部shell命令并使用C ++的Boost库读取其输出,但似乎该命令未运行或我无法访问输出。我以their documentation为例,写着:

#include <boost/process.hpp>
namespace bp = boost::process;

bool is_process_running(std::string p_name){
        string cmd = "ps aux 2>&1";
        bp::ipstream out;
        std::string line;
        bp::child c(cmd, bp::std_out > out);

        // the while is supposed to read each line of the output
        // but the execution doesn't enter here
        while(c.running() && std::getline(out, line) && !line.empty())
        {
            if(line.find(p_name) != std::string::npos)
            {
                return true;
            }
        }
        c.wait();
        return false;
}

目标是验证ps aux的每一行输出并搜索进程是否正在运行。那么,这可能是什么问题?或者,您可以为此提供一个简单的代码段吗?

2 个答案:

答案 0 :(得分:1)

我遇到了这个问题...我只能使用boost :: asio来使流程正常工作。

这是代码,希望对您有所帮助。下面的代码处理子进程的所有三个流。

唯一的外部文件是exename_,而tstring是std :: basic_string

cursor = RaDatabase.execute_sql(r'SHOW MASTER STATUS\G')

答案 1 :(得分:1)

只需使用shell(或使用bp::system):

Live On Coliru

#include <boost/process.hpp>
namespace bp = boost::process;

bool is_process_running(std::string p_name){
    std::vector<std::string> args { "-c", "ps aux 2>&1" };
    bp::ipstream out;
    bp::child c(bp::search_path("sh"), args, bp::std_out > out);

    for (std::string line; c.running() && std::getline(out, line);) {
        if (line.find(p_name) != std::string::npos) {
            return true;
        }
    }
    c.wait();

    return false;
}

#include <iostream>
int main() {
    std::cout << "bogus: " << is_process_running("bogus") << "\n";
    std::cout << "a.out: " << is_process_running("a.out") << "\n";
}

打印

bogus: 0
a.out: 1
相关问题