如何在打印后立即检索程序输出?

时间:2018-02-15 21:40:08

标签: boost boost-asio boost-process

我有一个boost :: process :: child。有很多关于如何在单个向量中获取所有stdout或stderr的示例,但在此方法中,您可以一次捕获所有数据。但是如何在子进程中打印行/字符时如何检索它们?

1 个答案:

答案 0 :(得分:3)

文档在这里:

使用ipstream

最简单的方法:

<强> Live On Coliru

#include <boost/process.hpp>
#include <iostream>

namespace bp = boost::process;

int main() {
    std::vector<std::string> args { 
        "-c", 
        R"--(for a in one two three four; do sleep "$(($RANDOM%2)).$(($RANDOM%10))"; echo "line $a"; done)--" };

    bp::ipstream output;
    bp::child p("/bin/bash", args, bp::std_out > output);

    std::string line;
    while (std::getline(output, line)) {
        std::cout << "Received: '" << line << "'" << std::endl;
    }
}

打印(例如):

At 0.409434s Received: 'line one'
At 0.813645s Received: 'line two'
At 1.2179s Received: 'line three'
At 2.92228s Received: 'line four'

使用async_pipe

这种方法更加通用,让你可以轻松地做到这一点。可能发生死锁的情况,比如当你想同时做其他事情而不是阻止输入时。

#include <boost/process.hpp>
#include <boost/process/async.hpp>
#include <boost/asio.hpp>
#include <iostream>

namespace bp = boost::process;
using boost::asio::mutable_buffer;

void read_loop(bp::async_pipe& p, mutable_buffer buf) {
    p.async_read_some(buf, [&p,buf](std::error_code ec, size_t n) {
        std::cout << "Received " << n << " bytes (" << ec.message() << "): '";
        std::cout.write(boost::asio::buffer_cast<char const*>(buf), n) << "'" << std::endl;
        if (!ec) read_loop(p, buf);
    });
}

int main() {
    boost::asio::io_service svc;

    std::vector<std::string> args { 
        "-c", 
        R"--(for a in one two three four; do sleep "$(($RANDOM%2)).$(($RANDOM%10))"; echo "line $a"; done)--" };

    bp::async_pipe output(svc);
    bp::child p("/bin/bash", args, bp::std_out > output, svc);

    char buf[1024];
    read_loop(output, bp::buffer(buf));

    svc.run();
}

enter image description here