2016-11-09 10 views
1

私はboost.processを使って別のプロセスを開始しています。 私はstdoutをキャプチャして、それを自分で印刷したいと思います。 問題は、出力が塊で印刷されるか、またはサブプロセスを停止するときだけです。 テストサブプロセスは、echo "test"を毎秒20回呼び出すpythonスクリプトです。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; 
    } 
} 

これは、バッファは、それがforwaredされる前に完全にする必要があるためか、出力のみ10秒ごとに出力しますか? 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"})))); 
関連する問題