/**
 * File: subprocess.c
 * ------------------
 * Implements the subprocess routines, which is similar to popen and allows
 * the parent process to spawn a child process, print to its standard output,
 * and then suspend until the child process has finished.
 */

#include <unistd.h>
#include <sys/wait.h>
#include "exit-utils.h"
#include <string.h>

typedef struct subprocess_t {
    pid_t childPid;  // PID of child process we can communicate with
    int writeFileDescriptor; // FD we can write to that child can read from via STDIN
} subprocess_t;

subprocess_t subprocess(char *command) {
    int fds[2];
    pipe(fds);
    pid_t pid = fork();
    if (pid == 0) {
        close(fds[1]);
        dup2(fds[0], STDIN_FILENO);
        close(fds[0]);
        char *argv[] = {"/bin/sh", "-c", command, NULL};
        execvp(argv[0], argv);
        exit(1);
    }

    subprocess_t process = { pid, fds[1] };
    close(fds[0]);
    return process;
}

int main(int argc, char *argv[]) {
    subprocess_t sp = subprocess("/usr/bin/sort");
    const char *words[] = {
        "felicity", "umbrage", "susurration", "halcyon", 
        "pulchritude", "ablution", "somnolent", "indefatigable"
    };

    for (size_t i = 0; i < sizeof(words) / sizeof(words[0]); i++) {
        dprintf(sp.writeFileDescriptor, "%s\n", words[i]);
    }
    close(sp.writeFileDescriptor);

    int status;
    pid_t pid = waitpid(sp.childPid, &status, 0);
    return pid == sp.childPid && WIFEXITED(status) ? WEXITSTATUS(status) : -127;
}
