C++ 关闭输入流后,boost::process::child将不会退出
在下面的示例中,我尝试将一些数据写入子进程,子进程处理数据并将其写入文件。关闭流后,父进程无限期地等待子进程完成。我不知道如何表明我已经写完了数据,并且希望子进程停止阅读并完成它正在做的任何事情。根据文件,我不认为这是我想要的 我错过了什么?我检查过了,但我宁愿先让实际代码与同步IO一起工作C++ 关闭输入流后,boost::process::child将不会退出,c++,boost,boost-process,C++,Boost,Boost Process,在下面的示例中,我尝试将一些数据写入子进程,子进程处理数据并将其写入文件。关闭流后,父进程无限期地等待子进程完成。我不知道如何表明我已经写完了数据,并且希望子进程停止阅读并完成它正在做的任何事情。根据文件,我不认为这是我想要的 我错过了什么?我检查过了,但我宁愿先让实际代码与同步IO一起工作 #include <boost/process.hpp> #include <iostream> namespace bp = boost::process; int mai
#include <boost/process.hpp>
#include <iostream>
namespace bp = boost::process;
int main(int argc, char **argv)
{
boost::process::opstream in{};
boost::process::child child("/path/to/test.py", bp::std_in < in);
in << "test1\n";
in << "test2\n";
in << "test3\n";
in << std::flush;
std::cerr << "Closing the stream…\n";
in.close();
std::cerr << "Waiting for the child to exit…\n";
child.wait(); // Parent seems to hang here.
return 0;
}
文档警告说,将同步IO用于子进程容易出现死锁 以下是对异步IO的最小重写:
#include <boost/process.hpp>
#include <iostream>
namespace bp = boost::process;
int main() {
boost::asio::io_context ioc;
bp::async_pipe in{ioc};
bp::child child("./test.py", bp::std_in < in, bp::std_out.close());
for (auto msg : { "test1\n", "test2\n", "test3\n" }) {
write(in, bp::buffer(msg, strlen(msg)));
}
std::cerr << "Closing the pipe…\n";
in.close();
std::cerr << "Waiting for the child to exit…\n";
ioc.run(); // already awaits completion
child.wait(); // Parent seems to hang here.
}
#包括
#包括
名称空间bp=boost::process;
int main(){
boost::asio::io\u上下文ioc;
{ioc}中的bp::async_管道;
bp::child child(“./test.py”,bp::std_in std::cerr检查源代码后,我发现至少在这种情况下,关闭流不会关闭相关管道。手动这样做确实解决了问题:
...
in.close();
in.pipe().close();
child.wait(); // Does not hang.
感谢您的全面回答!我刚才发现问题是由引起的。我会看看我的解决方案是否有效,然后可能会联系开发人员以验证这是预期的行为。我非常确定,因为我在过去多次看到此行为发生更改/被修复。我认为需要更好的文档感觉
#include <boost/process.hpp>
#include <iostream>
using namespace std::chrono_literals;
namespace bp = boost::process;
int main() {
boost::asio::io_context ioc;
bp::async_pipe in{ioc};
bp::child child("./test.py", bp::std_in < in, bp::std_out.close());
std::thread th([&] {
for (auto msg : { "test1\n", "test2\n", "test3\n" }) {
write(in, bp::buffer(msg, strlen(msg)));
std::this_thread::sleep_for(1s);
}
std::cerr << "Closing the pipe…\n";
in.close();
});
std::cerr << "Waiting for the child to exit…\n";
ioc.run(); // already awaits completion
th.join();
child.wait(); // Parent seems to hang here.
}
...
in.close();
in.pipe().close();
child.wait(); // Does not hang.