事实上,你的卧铺程序不会终止。run()
将运行到完成。
让我们首先让示例“真实”,以便它有一个实际的读取循环来读取超过 1 行:
std::vector<std::string> lines;
boost::asio::streambuf buffer;
std::function<void()> read_loop;
read_loop = [&] {
boost::asio::async_read_until(out, buffer, "\n", [&](boost::system::error_code code, std::size_t size) {
if (code) {
std::cerr << "Oops: " << code.message() << std::endl;
} else {
std::cerr << "received: " << size << " bytes" << std::endl;
auto b = buffers_begin(buffer.data()), m = b+size;
lines.emplace_back(b, m);
buffer.consume(size);
if (lines.size()<10) {
read_loop();
}
}
});
};
read_loop();
context.run();
您可以看到它尝试读取 10 行。
终止孩子
你可以杀死它:
if (lines.size()<10) {
read_loop();
} else {
c.terminate();
}
或关闭输出管道,导致相同(断管):
if (lines.size()<10) {
read_loop();
} else {
out.close();
}
德诺
我无法让它在 Coliru 上运行,但我将 first.exe 替换为:
#include <iostream>
#include <chrono>
#include <thread>
#include <random>
using namespace std;
static mt19937 prng{random_device{}()};
static auto l() { return uniform_int_distribution(5,20)(prng); }
static auto c() { return uniform_int_distribution('a','z')(prng); }
int main() {
while(true) {
cout << std::string(l(), c()) << endl;
this_thread::sleep_for(chrono::seconds(1));
}
}
并通过上述程序,完整:
#include <boost/process.hpp>
#include <boost/asio.hpp>
#include <boost/process/async.hpp>
#include <iostream>
#include <iomanip>
#include <regex>
int main() {
namespace bp = boost::process;
using namespace std::string_literals;
boost::asio::io_context context;
bp::async_pipe out(context);
bp::child c("./first.exe", bp::std_out > out, context);
std::vector<std::string> lines;
boost::asio::streambuf buffer;
std::function<void()> read_loop;
read_loop = [&] {
boost::asio::async_read_until(out, buffer, "\n", [&](boost::system::error_code code, std::size_t size) {
if (code) {
std::cerr << "Oops: " << code.message() << std::endl;
} else {
std::cerr << "received: " << size << " bytes" << std::endl;
auto b = buffers_begin(buffer.data()), m = b+size;
lines.emplace_back(b, m);
buffer.consume(size);
if (lines.size()<10) {
read_loop();
} else {
c.terminate();
}
}
});
};
read_loop();
context.run();
for (auto& line : lines) {
std::cout << std::quoted(std::regex_replace(line, std::regex("\\n"), "\\n"s)) << "\n";
}
return c.exit_code();
}
在我的系统上打印:
received: 19 bytes
received: 12 bytes
received: 20 bytes
received: 16 bytes
received: 6 bytes
received: 6 bytes
received: 20 bytes
received: 13 bytes
received: 16 bytes
received: 21 bytes
"dddddddddddddddddd\\n"
"lllllllllll\\n"
"jjjjjjjjjjjjjjjjjjj\\n"
"uuuuuuuuuuuuuuu\\n"
"yyyyy\\n"
"wwwww\\n"
"hhhhhhhhhhhhhhhhhhh\\n"
"qqqqqqqqqqqq\\n"
"aaaaaaaaaaaaaaa\\n"
"xxxxxxxxxxxxxxxxxxxx\\n"