boost :: process写入stdin

时间:2014-02-08 22:08:58

标签: c++ boost process stdin

我有一个线程启动一个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;
}

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

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

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

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

如何写入孩子的标准proc

1 个答案:

答案 0 :(得分:3)

这是一个改编自样本here的演示:

你可以看到它 Live on 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的示例down that page