在下面的示例中,我尝试将一些数据写入子进程,该子进程处理数据并将其写入文件。关闭流后,父进程无限期地等待子进程完成。我不知道如何表明我已完成写入数据,并希望子进程停止读取并完成它正在做的任何事情。根据文档调用终止会发送一个SIGKILL https://www.boost.org/doc/libs/1_73_0/doc/html/boost/process/child.html#idm45662292955280-bb我认为这不是我想要的。
我缺少什么?我检查了这个问题 https://stackoverflow.com/questions/44239499/close-the-stdin-of-boostprocess-child但我宁愿首先尝试使实际代码与同步 IO 一起工作。
#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;
}
test.py 只是将数据写入文件,如下所示:
#!/usr/local/homebrew/opt/[email protected] /cdn-cgi/l/email-protection/bin/python3
import sys
with open("/tmp/test.txt", "w") as f:
for line in sys.stdin:
f.write(line)
检查源代码后,我发现至少在这种情况下关闭流并没有关闭关联的管道。手动执行此操作确实解决了问题:
...
in.close();
in.pipe().close();
child.wait(); // Does not hang.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)