提升::p Rocess 写入 stdin

boost::process write to stdin

本文关键字:stdin 写入 提升 Rocess      更新时间:2023-10-16

我有一个线程启动了一个 boost::p rocess 应用程序,线程运行的代码如下:

void Service::Run()
{
    printf("Starting thread for service ID %in", 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: %in", 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: %in", exit_code);
    }
    catch(boost::system::system_error err)
    {
        printf("Something went wrong: %sn", err.what());
    }
    this->manager->ServiceDie(this->sid);
    return;
}

由于此函数是一个阻塞函数,它本质上是等待服务被终止(外部或根据需要;通过 stdin 输入以优雅地停止应用程序)。

我不知道如何写入子进程的 stdin。我试过这个:

*(this->stdIn) << "stopn";

在另一个线程(Manager类)中调用的 Service 类中的公共函数内。然而,这没有结果。

我怎样才能写到子proc的标准

下面是一个改编自此处示例的演示:

你可以看到它在Coliru Live上,可悲的是,这正在挑战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 << "somencookiesnforntasting";
    os.close();
    std::cout << is.rdbuf(); 
} 

输出:

emos
seikooc
rof
gnitsat

现在,如果你需要它真正的异步,还有另一个使用Boost Asio的示例在该页面的下方