#define _XOPEN_SOURCE 600

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

int main(void) {
    int master_fd = posix_openpt(O_RDWR | O_NOCTTY);
    if (master_fd == -1) {
        perror("posix_openpt");
        return 1;
    }

    if (grantpt(master_fd) == -1) {
        perror("grantpt");
        return 1;
    }

    if (unlockpt(master_fd) == -1) {
        perror("unlockpt");
        return 1;
    }

    char *slave_name = ptsname(master_fd);
    if (slave_name == NULL) {
        perror("ptsname");
        return 1;
    }

    pid_t pid = fork();

    if (pid == -1) {
        perror("fork");
        return 1;
    }

    if (pid == 0) {
        /*
           Child: create a new session.
           After this, the child has no controlling terminal.
        */
        if (setsid() == -1) {
            perror("setsid");
            _exit(1);
        }

        /*
           Open slave side. Do NOT use O_NOCTTY here if you want
           this PTY to become the child's controlling terminal.
        */
        int slave_fd = open(slave_name, O_RDWR);
        if (slave_fd == -1) {
            perror("open slave");
            _exit(1);
        }

        /*
           Connect terminal to stdin/stdout/stderr.
        */
        dup2(slave_fd, STDIN_FILENO);
        dup2(slave_fd, STDOUT_FILENO);
        dup2(slave_fd, STDERR_FILENO);

        if (slave_fd > STDERR_FILENO) {
            close(slave_fd);
        }

        close(master_fd);

        execlp("bash", "bash", NULL);
        perror("execlp");
        _exit(1);
    }

    /*
       Parent: terminal-emulator side.
       It talks to the child through master_fd.
    */

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

    /*
       Here you would normally:
       - read from keyboard/stdin and write to master_fd
       - read from master_fd and write to screen/stdout
    */

    waitpid(pid, NULL, 0);
    close(master_fd);

    return 0;
}
