2016-11-09 55 views
1

我正在使用boost.process啓動另一個進程。 我想捕獲標準輸出並自己打印。 問題是,輸出僅以塊或打印子進程打印。 測試子進程是一個python腳本,每秒調用echo "test" 20次。Boost.Process:捕獲的stdout被緩存到X的大小

void ExternalAppLauncher::setup() 
{ 
    boost::process::pipe stdout_p = boost::process::create_pipe(); 
    boost::process::pipe stderr_p = boost::process::create_pipe(); 

    { 
     file_descriptor_sink stdout_sink(stdout_p.sink, close_handle); 
     file_descriptor_sink stderr_sink(stderr_p.sink, close_handle); 
     file_descriptor_source stdout_source(stdout_p.source, close_handle); 
     file_descriptor_source stderr_source(stderr_p.source, close_handle); 

     out_stream.open(stdout_source); 
     err_stream.open(stderr_source); 

     childProcess.reset(new child(execute(
             set_args(args), 
             bind_stdout(stdout_sink), 
             bind_stderr(stderr_sink), 
             inherit_env(), 
             // Guarantees that the child process gets killed, even when this process recieves SIGKILL(9) instead of SIGINT(2) 
             on_exec_setup([](executor&) 
     { 
      ::prctl(PR_SET_PDEATHSIG, SIGKILL); 
     }) 
            ))); 
    } 
} 

// runs in another thread 
void ExternalAppLauncher::run() 
{ 
    std::string s; 
    while (std::getline(err_stream, s)) 
    { 
     std::cout << s; 
    } 
} 

這隻會每10秒輸出一次輸出,可能是因爲緩衝區在forwared之前需要滿了? 當我不打電話bind_stdout()輸出立即出現在控制檯上。 什麼可以解決這個問題?

謝謝!

回答

1

當我在線程How to capture standard out and print to both the console and a file during process runtime (C++/Boost.Process)中發現我運行的python腳本是罪魁禍首。 用export PYTHONUNBUFFERED=1取消激活python腳本的緩衝解決了它。 env var可以通過set_env傳遞給應用程序:

childProcess.reset(new child(execute(
            set_args(args), 
            start_in_dir(workingDir), 
            bind_stdout(stdout_sink), 
            bind_stderr(stderr_sink), 
            inherit_env(), 
            set_env(std::vector<std::string> {"PYTHONUNBUFFERED=1"}))));