There are many C++ subprocessing libraries out there, but none of them just work. The aim of this library is to allow you to write shell commands in C++ almost as if you were writing them in shell.
Full documentation for subprocess
is available here.
Note: Windows is not currently supported. I would like to pin down the library interface before adding compatibility for the OS.
It works exactly how you would expect it to work.
#include <subprocess.hpp>
using subprocess::command;
int main(int argc, char* argv[])
{
std::string owners;
(command{"ls", "-l", argv[1]} | command{"awk", "NR>1{print $3}"} | command{"sort"} | command{"uniq"} > owners).run();
// Use the owners as you wish
}
Instead of trying to emulate the subprocess interface from libraries in other languages, this library aims to use (and abuse) C++ operator overloading to achieve a shell-like syntax for writing shell commands.
You can write shell commands using the subprocess::command
class and use the resulting object to pipe I/O from/to standard streams, files, and variables.
Examples:
// Running a command
subprocess::command cmd{"touch", file_path}.run();
// Piping the output of a command to another command
cmd | subprocess::command{"uniq"};
You can use operator<
to redirect stdin to the command object.
Examples:
// Reading input from a file
cmd < std::filesystem::path{file_name};
cmd < "file_name";
// Reading input from a variable
std::string input{"abc"};
cmd < input;
// Reading from an already created fd
cmd < subprocess::file_descriptor{fd_no};
The following operators are available for redirecting stdout:
operator>
: Truncates the file and writes outputoperator>>
: Appends output to file if it already exists, otherwise creates one.
Examples:
// Redirecting stdout to stderr
cmd > subprocess::err();
// Redirecting stdout to a file
cmd > std::filesystem::path{file_name};
// or appending to a file
cmd >> std::filesystem::path{file_name};
// Capturing stdout in a variable
std::string var_name;
cmd > var_name;
The following operators are available for redirecting stdout:
operator>=
: Truncates the file and writes stderroperator>>=
: Appends stderr to file if it already exists, otherwise creates one.
Examples:
// Redirecting stderr to stdout
cmd >= subprocess::err();
// Redirecting stderr to a file
cmd >= std::filesystem::path{file_name};
// or appending to a file
cmd >>= std::filesystem::path{file_name};
// Capturing stderr in a variable
std::string var_name;
cmd >= var_name;
I would love your feedback! If you find any issues, feel free to log them.