boost::process 写入 stdin

5

我有一个线程启动了一个boost::process应用程序,代码如下:

void Service::Run()
{
    printf("Starting thread for service ID %i\n", this->sid);

    // Set up a stream sink for stdout, stderr and stdin
    bprocess::pipe pstdIn    = create_pipe();
    bprocess::pipe pstdOut   = create_pipe();
    file_descriptor_sink      fdSink(pstdIn.sink, close_handle);
    file_descriptor_source    fdSrc(pstdOut.sink, close_handle);

    // Set up the read write streams
    this->stdIn  = new fdistream(fdSink);
    this->stdOut = new fdostream(fdSrc);

    // Execute the service
    try
    {
        child proc = execute(
            set_args(this->args),
            inherit_env(),
            bind_stdin(fdSrc),

            throw_on_error()
        );

        printf("PID: %i\n", proc.pid);

        // Wait for the application to end then call a cleanup function
        int exit_code = wait_for_exit(proc);

        printf("Service died, error code: %i\n", exit_code);
    }
    catch(boost::system::system_error err)
    {
        printf("Something went wrong: %s\n", err.what());
    }

    this->manager->ServiceDie(this->sid);

    return;
}

由于这个函数是阻塞的,它会等待服务被杀死(外部或者我需要通过标准输入来优雅地停止应用程序)。

我不知道如何写入到子进程的标准输入。我已经尝试过这样:

*(this->stdIn) << "stop\n";

在另一个线程(Manager类)中调用的Service类中的公共函数内部。然而,这并没有产生任何结果。
我该如何写入子进程proc的标准输入?
1个回答

2
这是一个改编自这里示例的演示:

你可以在Coliru上实时查看,但很遗憾,这已经超出了Coliru的极限。也许以后会有:

#include <boost/process.hpp> 
#include <boost/assign/list_of.hpp> 
#include <string> 
#include <vector> 
#include <iostream> 

using namespace boost::process; 

int main() 
{ 
    std::string exec = find_executable_in_path("rev"); 
    std::vector<std::string> args = boost::assign::list_of("rev"); 

    context ctx; 
    ctx.environment = self::get_environment(); 
    ctx.stdin_behavior = capture_stream(); 
    ctx.stdout_behavior = capture_stream(); 
    child c = launch(exec, args, ctx); 

    postream &os = c.get_stdin();
    pistream &is = c.get_stdout(); 

    os << "some\ncookies\nfor\ntasting";
    os.close();

    std::cout << is.rdbuf(); 
} 

输出:

emos
seikooc
rof
gnitsat

现在,如果您需要真正的异步处理,还有另一个使用Boost Asio的示例,可以在该页面下方找到。


由于某些原因,我没有 get_stdin() 函数...不确定为什么,哦,我也没有 launch() - Zinglish
哎呀,我在回复中忘记提到我使用的 Boost::Process 版本了...我使用的是旧版本(0.5)。我已经更新了,会再试一遍。不过还是感谢你的有用回答!! - Zinglish
@Zinglish 你确定版本0.5已经过时了吗?你现在使用的是哪个版本? - Marc.2377

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接