DaanDeMeyer / reproc

A cross-platform (C99/C++11) process library
MIT License
552 stars 65 forks source link

Run a command with the pipe operator #88

Closed vebjornjr closed 1 year ago

vebjornjr commented 1 year ago

Hello.

Is it possible to run a command which uses the pipe operator ( | )? I sometimes wants to pipe the output of my command into either awk or sed for more processing before collecting the output.

A small toy example: ping 8.8.8.8 | sed 1q

Code:

//const vector<string> cmd = {"ping 8.8.8.8 | sed 1q"};
//const vector<string> cmd = {"ping", "8.8.8.8", "|", "sed", "1q"};
const vector<string> cmd = {"ping", "8.8.8.8 | sed 1q"};

reproc::options options;
options.deadline = reproc::milliseconds(100);
options.stop = {
    {reproc::stop::wait, reproc::deadline},                // wait for deadline
    {reproc::stop::terminate, reproc::milliseconds(500)},  // try to terminate (SIGINT) for a period
    {reproc::stop::kill, reproc::infinite},                // try to kill (SIGKILL) endlessly
};

string stdout;
string stderr;
reproc::run(cmd, options, reproc::sink::string(stdout), reproc::sink::string(stderr));

cout << fmt::format("stdout = {}", stdout) << endl;
cout << fmt::format("stderr = {}", stderr) << endl;

I can't get it to work no matter what variation of cmd I provide to run().

Thank you!

DaanDeMeyer commented 1 year ago

This requires a shell, reproc runs the command directly, not through a shell. Run the command through a shell if you want to use pipelines.