#include "proc.h"

proc_handler::proc_handler(io_event_loop& loop, string command)
  : net_handler<>(loop)
{
  pair<iohandle,iohandle> ios = iohandle::socketpair();

  ios.second.set_blocking(false);
  set_socket(ios.second, true);

  pid = fork();
  if (pid < 0)
    FATAL << status::syserr("fork");

  if (pid == 0) {
    // CHILD
    int r = dup2(ios.first.get_fd(), 0); // Get stdin from the socket
    if (r < 0) FATAL << status::syserr("dup2(0)");
    r = dup2(ios.first.get_fd(), 1); // Set stdout to go into the socket
    if (r < 0) FATAL << status::syserr("dup2(1)");

    execl(command.c_str(), command.c_str(), NULL);
    FATAL << status::syserr("execl");
  }
}

proc_handler::~proc_handler() {
  /* Kill the child */
  if (pid > 0)
    kill(pid, SIGTERM);
}

int proc_handler::incoming_data(constbuf buf) {
  WARN << buf;
  return buf.length();
}
