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

enum exit_codes {
    exit_success,
    exit_failure,
    exit_arguments,
    exit_process,
    exit_signal,
    exit_file
};

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);
}

void wait_process(int pid)
{
    int wr, status, exit_status;

    do {
        wr = wait(&status);
        if (wr == -1)
            terminate("wait", 1);
    } while (wr != pid);

    if (WIFEXITED(status)) {
        exit_status = WEXITSTATUS(status);
        if (exit_status != 0)
            printf("exited with code: %d\n", exit_status);
    } else
        printf("killed with signal: %d\n", WTERMSIG(status));
}

int launch_process(char *const cmds[])
{
    int pid;

    pid = fork();
    if (pid == -1)
        terminate("fork", exit_process);
    if (pid == 0) {
        execvp(cmds[0], cmds);
        terminate_exec("execvp", exit_process);
    }

    return pid;
}

int main(int argc, char **argv)
{
    int pid;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s program <args...>\n", argv[0]);
        return 1;
    }
    pid = launch_process(argv+1);
    wait_process(pid);

    return 0;
}
