Skip to content

Instantly share code, notes, and snippets.

@agateau-g
Created January 27, 2020 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agateau-g/012d840b00da8fe6c708680fe4897918 to your computer and use it in GitHub Desktop.
Save agateau-g/012d840b00da8fe6c708680fe4897918 to your computer and use it in GitHub Desktop.
C++ friendly execvp() wrapper
#include <algorithm>
#include <string>
#include <vector>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
using namespace std;
void child_run(const vector<string>& cmd) {
const char** args = new const char*[cmd.size() + 1];
transform(cmd.begin(), cmd.end(), args, [](const string& arg) {
return arg.c_str();
});
args[cmd.size()] = nullptr;
execvp(args[0], const_cast<char**>(args));
}
int run(const vector<string>& cmd) {
auto pid = fork();
if (pid == -1) {
return -1;
}
if (pid) {
int wstatus;
waitpid(pid, &wstatus, 0);
return WEXITSTATUS(wstatus);
} else {
child_run(cmd);
return -1;
}
}
int main(int argc, char** argv) {
return run({"ls", "/"});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment