使用BOOST进程在单独的线程中读取子进程标准输出

时间:2018-03-08 19:35:44

标签: c++ boost boost-asio boost-thread boost-process

我有一个主程序,它使用boost进程库来生成打印的子进程

Hello World !

每隔5秒在它的标准输出上。

我希望在主进程中可以读取/监视子进程的stdout,并在主程序中执行其他操作。

我已经尝试了boost asynchronous IOhttp://www.boost.org/doc/libs/1_66_0/doc/html/boost_process/tutorial.html)的示例,但所有这些似乎都阻止了主程序,直到子进程退出。

我们是否需要在单独的线程中读取childs stdout?有人可以提供一个示例,其中主程序可以同时执行其他操作而不是阻止来自孩子的stdout吗?

1 个答案:

答案 0 :(得分:4)

  

我已尝试过boost异步IO(http://www.boost.org/doc/libs/1_66_0/doc/html/boost_process/tutorial.html)的示例,但所有这些似乎都阻止了主程序,直到子进程退出。

再看一遍。 Asynchronous I/O下的所有示例都应该帮助您选择适合您的方法。

  

我们是否需要在单独的线程中读取childs stdout?有人可以提供一个示例,其中主程序可以同时执行其他操作而不是阻止来自孩子的stdout吗?

不,你不需要。虽然你可以并且取决于你想要实现的目标,但这可能是最简单的事情。

同步

您没有告诉我们您希望能做什么,所以让我们假设您只想打印输出:

<强> Live On Coliru

var settings = new JsonSerializerSettings();
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
settings.NullValueHandling = NullValueHandling.Ignore;
//you can add multiple settings and then use it
var bodyAsJson = JsonConvert.SerializeObject(body, Formatting.Indented, settings);

那是同步的,所以你不能在此期间工作

使用读者线程

那就像:

<强> Live On Coliru

bp::child c("/bin/bash", std::vector<std::string> { "-c", "for a in {1..10}; do sleep 2; echo 'Hello World !'; done" });
c.wait();

打印( Live On Coliru ):

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

namespace bp = boost::process;

int main() {
    bp::ipstream output;
    std::thread reader([&output] {
        std::string line;
        while (std::getline(output, line))
            std::cout << "Received: '" << line << "'" << std::endl;
    });

    bp::child c("/bin/bash",
        std::vector<std::string> { "-c", "for a in {1..10}; do sleep 2; echo 'Hello World ('$a')!'; done" },
        bp::std_out > output);

    while (c.running()) {
        std::this_thread::sleep_for(std::chrono::milliseconds(2793));
        std::cout << "(main thread working)" << std::endl;
    }

    std::cout << "(done)" << std::endl;
    c.wait();

    output.pipe().close();
    reader.join();
}

异步IO

使用无线程(嗯,只是主线程),看起来像:

<强> Live On Coliru

Received: 'Hello World (1)!'
(main thread working)
Received: 'Hello World (2)!'
(main thread working)
Received: 'Hello World (3)!'
Received: 'Hello World (4)!'
(main thread working)
Received: 'Hello World (5)!'
(main thread working)
Received: 'Hello World (6)!'
(main thread working)
Received: 'Hello World (7)!'
Received: 'Hello World (8)!'
(main thread working)
Received: 'Hello World (9)!'
(main thread working)
Received: 'Hello World (10)!'
(main thread working)
(done)

打印 Live On Coliru

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

namespace bp = boost::process;

struct OtherWork {
    using clock = std::chrono::high_resolution_clock;

    OtherWork(boost::asio::io_context& io) : timer(io) { }

    void start() {
        timer.expires_at(clock::time_point::max());
        loop();
    }

    void stop() {
        timer.expires_at(clock::time_point::min());
    }

  private:
    void loop() {
        if (timer.expires_at() == clock::time_point::min()) {
            std::cout << "(done)" << std::endl;
            return;
        }

        timer.expires_from_now(std::chrono::milliseconds(2793));
        timer.async_wait([=](boost::system::error_code ec) {
            if (!ec) {
                std::cout << "(other work in progress)" << std::endl;
                start();
            } else {
                std::cout << "(" << ec.message() << ")" << std::endl;
            }
        });
    }

    boost::asio::high_resolution_timer timer;
};

int main() {
    boost::asio::io_context io;
    bp::async_pipe output(io);

    OtherWork mainwork{io};

    bp::child c("/bin/bash", std::vector<std::string> { "-c", "for a in {1..10}; do sleep 2; echo 'Hello World ('$a')!'; done" },
            bp::std_out > output, io, bp::on_exit([&mainwork,&output](auto...) {
                    output.close();
                    mainwork.stop();
                }));

    std::function<void()> readloop = [&,buffer=std::array<char, 32>{}]() mutable {
        output.async_read_some(bp::buffer(buffer), [&](boost::system::error_code ec, size_t transferred) {
                if (transferred) {
                    std::cout << "Received: '";
                    while (transferred && buffer[transferred-1] == '\n') // strip newline(s)
                        --transferred;
                    std::cout.write(buffer.data(), transferred);
                    std::cout << "'" << std::endl;
                }

                if (ec)
                    std::cout << "Output pipe: " << ec.message() << std::endl;
                else
                    readloop();
            });
    };

    mainwork.start();
    readloop();
    io.run();
}