Boost :: process write to stdin

I have a thread that starts the boost :: process application, with code that the thread works as follows:

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;
}

Since this function is blocking, it essentially expects the service to be killed (Externally or as I need, enter via stdin to gracefully stop the application).

I do not know how to write in stdin of a child process. I tried this:

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

inside a public function in a class Servicethat is called in another thread ( Managerclass). However, this does not lead to results.

How can I write in stdin of a child proc?

+4
source share
1 answer

-, :

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

+3

Source: https://habr.com/ru/post/1525978/


All Articles