system-cmd-fork added

This commit is contained in:
vaclavt
2022-04-02 16:21:48 +02:00
parent 2607a50986
commit aaeb54d534
5 changed files with 50 additions and 21 deletions

View File

@@ -109,3 +109,32 @@ MlValue exec_system_cmd(const std::string &cmd) {
return std::vector<MlValue> { MlValue((long)cmd_retval), MlValue::string(cmd_output) };
}
MlValue exec_system_cmd_fork(const std::vector<std::string> &args) {
int pid = fork();
if (pid == 0) {
// Child process, execute the command
std::vector<char*> exec_args;
exec_args.reserve(args.size());
for (auto const& a : args)
exec_args.emplace_back(const_cast<char*>(a.c_str()));
exec_args.push_back(nullptr); // exec must end with null
execvp(args[0].c_str(), exec_args.data());
std::cerr << "execvp error: " << errno << ", " << strerror(errno) << std::endl;
exit(1); // indicate error, if here
} else if (pid > 0) {
// Parent process, child process is now independent
return std::vector<MlValue> { MlValue((long)0), MlValue::string("") };
} else {
// Fork error, still in parent process (there are no child process at this point)
return std::vector<MlValue> { MlValue((long)errno), MlValue::string(strerror(errno) ) };
}
}