#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/stropts.h>

int main(int argc, char* argv[])
{
  int pid;
  int fdm;
  int len;
  char buf[1024];

  if (argc < 2) {
    fprintf(stderr, "usage: %s command [args]...\n", argv[0]);
    exit(1);
  }

  if ((fdm = open("/dev/ptmx", O_RDWR)) < 0) {
    perror("/dev/ptmx");
    exit(1);
  }
  if (grantpt(fdm) < 0) {
    perror("grantpt");
    exit(1);
  }
  if (unlockpt(fdm) < 0) {
    perror("unlockpt");
    exit(1);
  }
  if ((pid = fork()) < 0) {
    perror("fork");
    exit(1);
  }
  if (pid == 0) {
    int i;
    int fds;
    char* slave;

    if ((slave = ptsname(fdm)) == NULL) {
      perror("ptsname");
      exit(1);
    }
    if ((fds = open(slave, O_RDWR)) < 0) {
      perror(slave);
      exit(1);
    }
/* For Solaris, uncomment this.

    if (ioctl(fds, I_PUSH, "ptem") < 0) {
      perror("ioctl:I_PUSH:ptem");
      exit(1);
    }
    if (ioctl(fds, I_PUSH, "ldterm") < 0) {
      perror("ioctl:I_PUSH:ldterm");
      exit(1);
    }
*/
    dup2(fds, 0);
    dup2(fds, 1);
    dup2(fds, 2);

    for (i=3; i < 256; i++)
      close(i);

    execvp(argv[1], &argv[1]);
    perror(argv[1]);
    exit(1);
  }

  while ((len = read(fdm, buf, sizeof(buf))) > 0)
    write(1, buf, len);

  return 0;
}
