如何使用 c++ libboost 运行进程并获取其输出?

How to run a process and get its output using c++ libboost?

本文关键字:获取 输出 进程 何使用 c++ libboost 运行      更新时间:2023-10-16

我正在尝试运行外部 shell 命令并使用 Boost 库读取其输出C++但似乎该命令未运行或我只是无法访问输出。我使用他们的文档作为示例并编写了以下内容:

#include <boost/process.hpp>
namespace bp = boost::process;
bool is_process_running(std::string p_name){
string cmd = "ps aux 2>&1";
bp::ipstream out;
std::string line;
bp::child c(cmd, bp::std_out > out);
// the while is supposed to read each line of the output
// but the execution doesn't enter here
while(c.running() && std::getline(out, line) && !line.empty())
{
if(line.find(p_name) != std::string::npos)
{
return true;
}
}
c.wait();
return false;
}

目标是验证ps aux的每一行输出,并搜索进程是否正在运行。那么,这里可能有什么问题呢?或者,您能提供一个简单的片段来执行此操作吗?

只需使用 shell(或使用bp::system(:

住在科里鲁

#include <boost/process.hpp>
namespace bp = boost::process;
bool is_process_running(std::string p_name){
std::vector<std::string> args { "-c", "ps aux 2>&1" };
bp::ipstream out;
bp::child c(bp::search_path("sh"), args, bp::std_out > out);
for (std::string line; c.running() && std::getline(out, line);) {
if (line.find(p_name) != std::string::npos) {
return true;
}
}
c.wait();
return false;
}
#include <iostream>
int main() {
std::cout << "bogus: " << is_process_running("bogus") << "n";
std::cout << "a.out: " << is_process_running("a.out") << "n";
}

指纹

bogus: 0
a.out: 1

我遇到了这个问题... 我只能使用 boost::asio 让进程工作。

这是代码,希望这会有所帮助。 下面的代码处理子进程的所有三个流。

唯一的外部是 exename_,字符串是 std::basic_string

void UBC::Run(
const tstring& args,
const std::string& input,
std::string& output,
std::string& error)
{
using namespace boost;
asio::io_service ios;
std::vector<char> vOut(128 << 10);
auto outBuffer{ asio::buffer(vOut) };
process::async_pipe pipeOut(ios);
std::function<void(const system::error_code & ec, std::size_t n)> onStdOut;
onStdOut = [&](const system::error_code & ec, size_t n)
{
output.reserve(output.size() + n);
output.insert(output.end(), vOut.begin(), vOut.begin() + n);
if (!ec)
{
asio::async_read(pipeOut, outBuffer, onStdOut);
}
};
std::vector<char> vErr(128 << 10);
auto errBuffer{ asio::buffer(vErr) };
process::async_pipe pipeErr(ios);
std::function<void(const system::error_code & ec, std::size_t n)> onStdErr;
onStdErr = [&](const system::error_code & ec, size_t n)
{
error.reserve(error.size() + n);
error.insert(error.end(), vErr.begin(), vErr.begin() + n);
if (!ec)
{
asio::async_read(pipeErr, errBuffer, onStdErr);
}
};
auto inBuffer{ asio::buffer(input) };
process::async_pipe pipeIn(ios);
process::child c(
tstring(exeName_) + _T(" ") + args, 
process::std_out > pipeOut, 
process::std_err > pipeErr, 
process::std_in < pipeIn
);

asio::async_write(pipeIn, inBuffer, 
[&](const system::error_code & ec, std::size_t n) 
{
pipeIn.async_close();
});
asio::async_read(pipeOut, outBuffer, onStdOut);
asio::async_read(pipeErr, errBuffer, onStdErr);
ios.run();
c.wait();
}