gpt4 book ai didi

c++ - boost 1.71.0 : How to get process output?

转载 作者:行者123 更新时间:2023-12-04 07:18:41 28 4
gpt4 key购买 nike

我有这样的代码,在 Ubuntu 18.04 上运行良好和 Boost 1.65.0 :

// See https://www.boost.org/doc/libs/1_65_0/doc/html/boost_process/tutorial.html
std::pair<int, std::string> runCommandAndGetOutput(const std::string & cmd, const std::vector<std::string> & args)
{
namespace bp = boost::process;
boost::asio::io_service ios;
std::future<std::string> data;
bp::child c(cmd, bp::args(args), bp::std_in.close(), bp::std_out > data, bp::std_err > bp::null, ios);
ios.run();
if (c.exit_code()) {
std::cerr << "Command '" << cmd << "' failed with return value: " << c.exit_code();
}
return { c.exit_code(), data.get() };
}
但是,升级到 Ubuntu 20.04 后和 Boost 1.71.0这不再编译了,因为似乎 boost::asio::io_service已弃用且不再存在。
谷歌搜索后,我意识到我必须使用 boost::asio::io_context反而。
好的:
std::pair<int, std::string> runCommandAndGetOutput(const std::string & cmd, const std::vector<std::string> & args)
{
namespace bp = boost::process;
boost::asio::io_context ioc;
std::future<std::string> data;
bp::child c(cmd, bp::args(args), bp::std_in.close(), bp::std_out > data, bp::std_err > bp::null, ioc);
ioc.run();
if (c.exit_code()) {
std::cerr << "Command '" << cmd << "' failed with return value: " << c.exit_code();
}
return { c.exit_code(), data.get() };
}
这可以编译,但不起作用。试图运行例如 /usr/bin/free返回退出代码 383这没有任何意义。
使这变得困难的是 Boost 1.71.0的文档仍在使用 io_service :
https://www.boost.org/doc/libs/1_71_0/doc/html/boost_process/tutorial.html
有谁知道这应该怎么做?

最佳答案

您需要 wait直到 child 完成。
exit_code - "获取exit_code。如果 child 没有被等待或被终止,则返回值没有任何意义。"

#include "boost/process.hpp"

#include <iostream>

std::pair<int, std::string> runCommandAndGetOutput(
const std::string& cmd, const std::vector<std::string>& args) {
namespace bp = boost::process;
boost::asio::io_context ioc;
std::future<std::string> data;
bp::child c(cmd, bp::args(args), bp::std_in.close(), bp::std_out > data,
bp::std_err > bp::null, ioc);
ioc.run();

c.wait(); // <---- here

if(c.exit_code()) {
std::cerr << "Command '" << cmd
<< "' failed with return value: " << c.exit_code();
}
return {c.exit_code(), data.get()};
}

int main() {
auto rv = runCommandAndGetOutput("/usr/bin/free", {});

std::cout << "\n----------\n" << rv.second << '\n' << rv.first << '\n';
}

关于c++ - boost 1.71.0 : How to get process output?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68635838/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com