Support feeding the child process data on stdin

This commit is contained in:
Dennis Klein 2018-10-10 19:01:40 +02:00 committed by Dennis Klein
parent 9f325451e5
commit 3a1b769937
2 changed files with 21 additions and 7 deletions

View File

@ -12,6 +12,7 @@
#include <iostream> #include <iostream>
#include <sstream> #include <sstream>
#include <thread>
using namespace std; using namespace std;
@ -30,23 +31,33 @@ namespace tools
* @param[in] log_prefix How to prefix each captured output line with * @param[in] log_prefix How to prefix each captured output line with
* @return Captured stdout output and exit code * @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; execute_result result;
stringstream out; stringstream out;
// print full line thread-safe // print full line thread-safe
stringstream printCmd; stringstream printCmd;
printCmd << prefix << cmd << "\n"; printCmd << prefix << " " << cmd << "\n";
cout << printCmd.str() << flush; cout << printCmd.str() << flush;
out << prefix << cmd << endl; out << prefix << cmd << endl;
// Execute command and capture stdout, add prefix line by line // Execute command and capture stdout, add prefix line by line
boost::process::ipstream stdout; boost::process::ipstream c_stdout;
boost::process::child c(cmd, boost::process::std_out > 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; string line;
while (getline(stdout, line)) while (getline(c_stdout, line))
{ {
// print full line thread-safe // print full line thread-safe
stringstream printLine; stringstream printLine;

View File

@ -32,10 +32,13 @@ struct execute_result
* and exit code. * and exit code.
* *
* @param[in] cmd Command to execute * @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 * @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 tools */
} /* namespace mq */ } /* namespace mq */