spawn.cc
1 // Copyright 2018, Beeri 15. All rights reserved.
2 // Author: Roman Gershman (romange@gmail.com)
3 //
4 #include <errno.h>
5 #include <spawn.h>
6 #include <sys/wait.h>
7 #include <unistd.h>
8 
9 #include <string>
10 
11 #include "util/spawn.h"
12 
13 extern "C" char **environ;
14 
15 namespace util {
16 
17 // Runs a child process efficiently.
18 // argv must be null terminated array of arguments where the first item in the array is the base
19 // name of the executable passed by path.
20 // Returns 0 if child process run successfully and updates child_status with its return status.
21 static int spawn(const char* path, char* argv[], int* child_status) {
22  pid_t pid;
23  // posix_spawn in this configuration calls vfork without duplicating parents
24  // virtual memory for the child. That's all we want.
25  int status = posix_spawn(&pid, path, NULL, NULL, argv, environ);
26  if (status != 0)
27  return status;
28 
29  if (waitpid(pid, child_status, 0) == -1)
30  return errno;
31  return 0;
32 }
33 
34 int sh_exec(const char* cmd) {
35  char sh_bin[] = "sh";
36  char arg1[] = "-c";
37 
38  std::string cmd2(cmd);
39 
40  char* argv[] = {sh_bin, arg1, &cmd2.front(), NULL};
41  int child_status = 0;
42  return spawn("/bin/sh", argv, &child_status);
43 }
44 
45 } // namespace util