Created
January 27, 2020 15:40
-
-
Save agateau-g/012d840b00da8fe6c708680fe4897918 to your computer and use it in GitHub Desktop.
C++ friendly execvp() wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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