2

我有一个 boost::process::child。有很多关于如何在单个向量中获取其所有标准输出或标准错误的示例,但在这种方法中,您可以一次捕获所有数据。但是如何在子进程中打印后立即检索行/字符?

4

1 回答 1

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();
}

在此处输入图像描述

于 2018-02-15T22:52:52.407 回答