#define _XOPEN_SOURCE	600

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <errno.h>

// man 7 pty

#define K	1024

int main(int argc, char *argv[])
{
  struct termios tio;
  struct winsize ws;
  pid_t pid;
  int pty, tty, r;
  char *pts, buf[K];

  if (tcgetattr(0, &tio) < 0) {
    perror("tcgetattr");
    exit(1);
  }
  if (ioctl(0, TIOCGWINSZ, &ws) < 0) {
    fprintf(stderr,"getting winsize\n");
    exit(1);
  }
  if ((pty = posix_openpt(O_RDWR | O_NOCTTY)) < 0) {
    perror("openpt");
    exit(1);
  }
  if (grantpt(pty) < 0) {
    perror("grantpt");
    exit(1);
  }
  if (unlockpt(pty) < 0) {
    perror("unlockpt");
    exit(1);
  }
  if ((pts = ptsname(pty)) == NULL) {
    perror("ptsname");
    exit(1);
  }
  
  pid = fork();
  if (pid < 0) {
    perror("fork");
    exit(1);
  }
  if (pid > 0) {
    while ((r = read(pty, buf, K)) > 0) {
      fprintf(stderr,"%.*s", r, buf);
    }
  } else {
    if ((tty = open(pts, O_RDWR)) < 0) {
      perror("slave open");
      exit(1);
    }
    dup2(tty, 0);
    dup2(tty, 1);
    dup2(tty, 2);
    close(tty);
    if (tcsetattr(0, TCSANOW, &tio) < 0) {
      perror("tcsetattr");
    }
    if (ioctl(0, TIOCSWINSZ, &ws) < 0) {
      fprintf(stderr,"winsize\n");
    }
    execlp("stty", "stty", "-a", NULL);
  }
}
