
#include "other.h"
#include "ttyexec.h"


void TtyForkExec::err (char* msg, bool am_child =0)
{
  if(am_child) {
    fprintf(stderr,"\nERROR IN CHILD: %s\n",msg);
    exit(1);
  }
  else {
    ErrorMessage = msg;  
  }
}

int TtyForkExec::ForkExecv (char* name,
			    char* argv[])
{
  if(have_forked)
    { err("Attempt to again forkexec a forkexec'ed TtyForkExec.");
      return -1; }

  have_forked = 1;

  if(! the_ptytty.Has_pair())
    { err("Couldnt aquire ptytty pair."); return -1; }

  int pid = fork();
  switch (pid) {
  case 0:  child(name,argv,NULL); exit(1);      // child
  case -1: err("Fork failed."); return -1;      // failure
  default: return pid;                          // parent
  }
}

const int READ =0, WRITE =1, ERROR =2;

void TtyForkExec::child (char*name,char*argv[],char*envp[])
{
  ::close(READ);
  ::close(WRITE);

  the_ptytty.make_slave_tty_the_controlling_tty();

  ::close(ERROR);

  // setup stdout and stderr.  (stdin was setup by control open).
  (void) dup2(the_ptytty.slave_tty(), WRITE);
  (void) dup2(the_ptytty.slave_tty(), ERROR);

  execve(name,argv,envp);
  err("exec failed");
  exit(1);
}
