【发布时间】:2022-06-30 04:29:59
【问题描述】:
我遇到了障碍。下面的代码有问题,但这只是一个演示;我想先把高层逻辑弄对。
两个启动应用程序在到达“就绪”状态之前输出了很多启动信息。在这种状态下,程序 A 已准备好通过标准输入进行用户输入。程序 B 只是通过网络连接进行监听——摄取和记录数据。
理想情况下,使用这个示例程序,我应该能够“实时”看到程序 B 的输出。但是在每次循环迭代中,什么都没有发生;我不确定它是否通过管道接收输入。
我之前使用bp::opstream 写入孩子的--Program A--stdin。我知道程序 A 是否通过其 async_pipe 接受了某些命令,Progam B show 还会显示一些日志记录信息(例如“trip”)。这些是窗口控制台应用程序,我使用 Boost C++ 作为子进程与它们进行交互。
有人知道发生了什么吗?
std::size_t read_loop(bp::async_pipe& p, mutable_buffer buf, boost::system::error_code &err)
{
return p.read_some(buf, err);
}
void read_loop_async(bp::async_pipe& p, mutable_buffer buf, std::error_code &err) {
p.async_read_some(buf, [&p, buf, &err](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;
err = ec;
if (!ec)
read_loop_async(p, buf, err);
});
}
void write_pipe(bp::async_pipe&p, mutable_buffer buf)
{
ba::async_write(p, buf, [](boost::system::error_code ec, std::size_t sz)
{
std::cout << "Size Written " << sz << " Ec: " << ec << " " << ec.message() << '\n';
});
}
int main()
{
bp::opstream sendToChild;
string wd = "<---path-to-working-dir----->";
ba::io_service ios;
string bin = "<path-to-bin-and-name>";
bp::async_pipe input_pipe(ios);
bp::async_pipe output_pipe(ios);
bp::child c(bin, "arg1", "arg2", "arg3", bp::std_out > output_pipe,
bp::std_in < input_pipe, ios, bp::start_dir(wd.c_str()));
size_t size = 8192;
string input;
vector <char> buffer(size);
boost::system::error_code ec;
std::error_code err;
ios.run();
while (1)
{
//show read whatever is available from the childs output_pipe
read_loop_async(output_pipe, bp::buffer(buffer), err);
cout << "\nBoot-> ";
cin >> input;
if (input == "1")
{
cout << " send input to child: ";
cin >> input;
//send commands to the child, Program A
//originally
//sendToChild << input<< endl;
write_pipe(input_pipe, bp::buffer(input));
}
if (input == "quit")
{
//sendToChild << input << endl;
read_loop_async(output_pipe, bp::buffer(buffer), err);
break;
}
ios.poll(ec);
ios.restart();
}
c.join();
cout << "done...";
cin >> input;
}
这是我关注的链接: How to retrieve program output as soon as it printed?
【问题讨论】:
标签: c++ boost visual-studio-2017 boost-asio async-pipe