12 #include <boost/asio/read_until.hpp>
13 #include <boost/process/args.hpp>
17 namespace bp = boost::process;
20 : m_io_ctx(ctx), m_args(std::move(args)), m_stdout{ctx}, m_stderr{ctx} {
21 if (m_args.size() < 1) {
22 throw std::invalid_argument(
"No arguments provided");
24 m_args[0] = bp::search_path(m_args[0]).native();
31 assert(!m_proc.valid());
45 bp::std_out > m_stdout.pipe,
46 bp::std_err > m_stderr.pipe,
48 bp::on_exit = [
this](
int exit,
const std::error_code& ec_in) {
52 m_result = {exit, ec_in};
56 AsyncReadStream(m_stdout);
57 AsyncReadStream(m_stderr);
58 return m_promise.get_future();
61 std::error_code AsyncProcess::Abort() noexcept {
63 return std::make_error_code(std::errc::no_such_process);
71 std::optional<pid_t> AsyncProcess::GetPid() const noexcept {
78 std::error_code AsyncProcess::Signal(
int sig) noexcept {
80 return std::make_error_code(std::errc::no_such_process);
83 pid_t
id = m_proc.id();
84 int err = kill(
id, sig);
85 return std::make_error_code(
static_cast<std::errc
>(err));
88 bool AsyncProcess::IsRunning() const noexcept {
92 return m_proc.valid() && !m_result.has_value();
95 void AsyncProcess::AsyncReadStream(AsyncProcess::Pipe& pipe) {
97 boost::asio::async_read_until(pipe.pipe,
100 [
this, &pipe](
const boost::system::error_code& ec, std::size_t) {
108 std::istream is(&pipe.buffer);
109 std::string remaining(pipe.buffer.size(),
'\0');
110 is.read(remaining.data(), remaining.size());
111 pipe.signal(m_pid, remaining);
122 std::istream is(&pipe.buffer);
124 std::getline(is, line);
127 line.push_back(
'\n');
128 pipe.signal(m_pid, line);
130 AsyncReadStream(pipe);
134 void AsyncProcess::CheckCompleted() {
136 if (!m_result.has_value() || m_stdout.pipe.is_open() || m_stderr.pipe.is_open()) {
141 m_promise.set_exception(std::system_error(m_result->ec));
143 m_promise.set_value(m_result->exit_code);
daq::AsyncProcess class definition
virtual ~AsyncProcess() noexcept
boost::future< int > Initiate() override
Starts process and asynchronous operations that read stdout and stderr.
AsyncProcess(boost::asio::io_context &ctx, std::vector< std::string > args)
Constructor.