Skip to content

Commit

Permalink
Support feeding the child process data on stdin
Browse files Browse the repository at this point in the history
  • Loading branch information
dennisklein committed Oct 10, 2018
1 parent 9f32545 commit 3a1b769
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
21 changes: 16 additions & 5 deletions fairmq/tools/Process.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

#include <iostream>
#include <sstream>
#include <thread>

using namespace std;

Expand All @@ -30,23 +31,33 @@ namespace tools
* @param[in] log_prefix How to prefix each captured output line with
* @return Captured stdout output and exit code
*/
execute_result execute(const string& cmd, const string& prefix)
execute_result execute(const string& cmd, const string& prefix, const string& input)
{
execute_result result;
stringstream out;

// print full line thread-safe
stringstream printCmd;
printCmd << prefix << cmd << "\n";
printCmd << prefix << " " << cmd << "\n";
cout << printCmd.str() << flush;

out << prefix << cmd << endl;

// Execute command and capture stdout, add prefix line by line
boost::process::ipstream stdout;
boost::process::child c(cmd, boost::process::std_out > stdout);
boost::process::ipstream c_stdout;
boost::process::opstream c_stdin;
boost::process::child c(
cmd, boost::process::std_out > c_stdout, boost::process::std_in < c_stdin);

// Optionally, write to stdin of the child
if (input != "") {
this_thread::sleep_for(chrono::milliseconds(100));
c_stdin << input;
c_stdin.flush();
}

string line;
while (getline(stdout, line))
while (getline(c_stdout, line))
{
// print full line thread-safe
stringstream printLine;
Expand Down
7 changes: 5 additions & 2 deletions fairmq/tools/Process.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,13 @@ struct execute_result
* and exit code.
*
* @param[in] cmd Command to execute
* @param[in] log_prefix How to prefix each captured output line with
* @param[in] prefix How to prefix each captured output line with
* @param[in] input Data which is sent to stdin of the child process
* @return Captured stdout output and exit code
*/
execute_result execute(const std::string& cmd, const std::string& prefix = "");
execute_result execute(const std::string& cmd,
const std::string& prefix = "",
const std::string& input = "");

} /* namespace tools */
} /* namespace mq */
Expand Down

0 comments on commit 3a1b769

Please sign in to comment.