Skip to content
Repos

mologram

C++ 1.1 KB40 lines Opens in site

Directory Raw Download

#include "mologram/ProcessRunner.hpp"

#include <cerrno>
#include <fcntl.h>
#include <sys/wait.h>
#include <unistd.h>

namespace mologram {

int ProcessRunner::capture(const std::vector<std::string>& argv, std::string& out) {
  if (argv.empty()) return -1;
  int fds[2];
  if (::pipe(fds) != 0) return -1;
  std::vector<char*> args;
  for (const auto& a : argv) args.push_back(const_cast<char*>(a.c_str()));
  args.push_back(nullptr);
  pid_t pid = ::fork();
  if (pid < 0) { ::close(fds[0]); ::close(fds[1]); return -1; }
  if (pid == 0) {
    int nul = ::open("/dev/null", O_RDWR);
    if (nul >= 0) { ::dup2(nul, 0); ::dup2(nul, 2); }
    ::dup2(fds[1], 1);
    ::close(fds[0]); ::close(fds[1]);
    ::execvp(args[0], args.data());
    _exit(127);
  }
  ::close(fds[1]);
  char buf[65536];
  for (;;) {
    ssize_t n = ::read(fds[0], buf, sizeof(buf));
    if (n > 0) out.append(buf, (size_t)n);
    else if (n == 0 || errno != EINTR) break;
  }
  ::close(fds[0]);
  int st = 0;
  ::waitpid(pid, &st, 0);
  return WIFEXITED(st) ? WEXITSTATUS(st) : -1;
}

}  // namespace mologram
34.6ms