【问题标题】:How to retrieve program output as soon as it printed?如何在打印后立即检索程序输出?
【发布时间】:2018-02-15 21:40:08
【问题描述】:

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

【问题讨论】:

    标签: boost boost-asio boost-process


    【解决方案1】:

    文档在这里:

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

    【讨论】:

    • 感谢您的回答。顺便说一句,您使用的是什么桌面?
    • @LPCWSTR 那是 tmux + powerline (我主要使用 i3wm 作为窗口管理器,但它不可见)
    猜你喜欢
    • 2020-11-02
    • 2017-02-16
    • 2013-12-27
    • 2010-09-25
    • 2010-11-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    相关资源
    最近更新 更多