boost :: process :: child在关闭输入流后不会退出 [英] boost::process::child will not exit after closing input stream

查看:127
本文介绍了boost :: process :: child在关闭输入流后不会退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,我尝试将一些数据写入子进程,该子进程处理该数据并将其写入文件.关闭流后,父进程将无限期等待子进程完成.我不知所措,不知道如何指示我已经完成了数据写入,并希望子进程停止读取并完成所有操作.根据文档,请终止会发送 SIGKILL ,我认为这不是我想要的.

In the following example I try to write some data to a child process, which processes the data and writes it to a file. After closing the stream the parent process waits indefinitely for the child to finish. I am at a loss to know how to indicate that I’m done writing the data and would like the child process to stop reading and finish whatever it is doing. According to the documentation calling terminate would send a SIGKILL which I don’t think is what I want.

我想念什么?我检查了这个问题,但我宁愿尝试使实际代码与同步IO优先.

What am I missing? I checked this question but I would rather try to make the actual code work with synchronous IO first.

#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只是将数据写入文件,如下所示:

test.py just writes the data to a file like so:

#!/usr/local/homebrew/opt/python@3.8/bin/python3

import sys

with open("/tmp/test.txt", "w") as f:
    for line in sys.stdin:
        f.write(line)

推荐答案

检查源代码后,我发现至少在这种情况下,关闭流不会关闭关联的管道.手动执行确实可以解决问题:

After inspecting the source code, I found out that closing the stream did not close the associated pipe at least in this case. Doing that manually did solve the issue:

...
in.close();
in.pipe().close();
child.wait(); // Does not hang.

这篇关于boost :: process :: child在关闭输入流后不会退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆