#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <pty.h>

static void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

void terminate_exec(const char *msg, int code)
{
    fflush(stderr);
    perror(msg);
    _exit(code);
}

static int child_process(int fd_master, int fd_slave, const char *name_slave)
{
    int pid, ret;

    pid = fork();
    if (pid == -1)
        terminate("fork", 1);

    if (pid == 0) {
        ret = setsid();
        if (ret == -1)
            terminate("setsid", 1);

        dup2(fd_slave, 0);
        dup2(fd_slave, 1);
        dup2(fd_slave, 2);
        close(fd_master);
        close(fd_slave);
        execlp("bash", "bash", NULL);
        terminate_exec("bash", 1);
    }

    return pid;
}

int main()
{
    int fd_master, fd_slave, ret, pid;
    char *name_slave;

    ret = openpty(&fd_master, &fd_slave, name_slave, NULL, NULL);
    if (ret == -1)
        terminate("openpty", 1);

    pid = child_process(fd_master, fd_slave, name_slave);

    printf("child is using slave PTY: %s\n", name_slave);

    waitpid(pid, NULL, 0);
    close(fd_master);
    close(fd_slave);

    return 0;
}
