如何在打印输出后立即检索程序输出? [英] How to retrieve program output as soon as it printed?

查看:84
本文介绍了如何在打印输出后立即检索程序输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a boost::process::child. There are many examples on how to get all its stdout or stderr in a single vector, but in this method you capture all data at once. But how to retrieve lines/characters as soon as they are printed in child process?

推荐答案

文档在这里:

异步IO

最简单的方法:

在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

此方法的用途更加广泛,可让您处理可能发生死锁的困难"情况,例如当您想同时执行其他操作而不是阻塞输入时.

Using async_pipe

This method is much more versatile and lets you do the "hard" cases where deadlock could occur, like when you want to do other things at the same time instead of blocking for input.

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

这篇关于如何在打印输出后立即检索程序输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆