system-cmd-fork added
This commit is contained in:
29
ml_io.cpp
29
ml_io.cpp
@@ -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) ) };
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user