diff --git a/main b/main index be9f84c..b299c97 100755 Binary files a/main and b/main differ diff --git a/subprocess.hpp b/subprocess.hpp index c8d6774..b02e64f 100755 --- a/subprocess.hpp +++ b/subprocess.hpp @@ -542,6 +542,9 @@ public: vargs_ = util::split(cmd_args); init_args(std::forward(args)...); + // Setup the communication channels of the Popen class + stream_.setup_comm_channels(); + if (!defer_process_start_) execute_process(); } @@ -551,6 +554,9 @@ public: vargs_.insert(vargs_.end(), cmd_args.begin(), cmd_args.end()); init_args(std::forward(args)...); + // Setup the communication channels of the Popen class + stream_.setup_comm_channels(); + if (!defer_process_start_) execute_process(); } @@ -640,8 +646,9 @@ void Popen::init_args(F&& farg, Args&&... args) void Popen::populate_c_argv() { - cargv_.reserve(vargs_.size()); + cargv_.reserve(vargs_.size() + 1); for (auto& arg : vargs_) cargv_.push_back(&arg[0]); + cargv_.push_back(nullptr); } void Popen::start_process() throw (CalledProcessError, OSError) @@ -767,8 +774,6 @@ void Popen::execute_process() throw (CalledProcessError, OSError) throw exp; } - // Setup the communication channels of the Popen class - stream_.setup_comm_channels(); } } @@ -1086,6 +1091,22 @@ namespace detail { return Popen(std::forward(farg), std::forward(args)...).wait(); } + + void pipeline_impl(std::vector& cmds) { /* EMPTY IMPL */ } + + template + void pipeline_impl(std::vector& cmds, + const std::string& cmd, + Args&&... args) + { + if (cmds.size() == 0) { + cmds.emplace_back(cmd, output{PIPE}, defer_spawn{true}); + } else { + cmds.emplace_back(cmd, input{cmds.back().output()}, output{PIPE}, defer_spawn{true}); + } + + pipeline_impl(cmds, std::forward(args)...); + } } @@ -1115,4 +1136,15 @@ OutBuffer check_output(const std::string& arg, Args&&... args) // Piping Support +template +// Args expected to be std::initializer_list +OutBuffer pipeline(Args&&... args) +{ + std::vector pcmds; + detail::pipeline_impl(pcmds, std::forward(args)...); + + for (auto& p : pcmds) p.start_process(); + return (pcmds.back().communicate().first); +} + }; diff --git a/test/test_subprocess.cc b/test/test_subprocess.cc index 2a2a8c3..2c35208 100755 --- a/test/test_subprocess.cc +++ b/test/test_subprocess.cc @@ -21,8 +21,15 @@ void test_piping() std::cout << res.buf.data() << std::endl; } +void test_easy_piping() +{ + auto res = pipeline("cat ../subprocess.hpp", "grep Args", "grep template"); + std::cout << res.buf.data() << std::endl; +} + int main() { - test_input(); - test_piping(); + //test_input(); + //test_piping(); + test_easy_piping(); return 0; }