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

enum exit_codes {
    exit_arguments = 1,
    exit_process
};

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

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

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

    return pid;
}

void iterate_process(int pid)
{
    int status, exit_status, sr, wr;
    struct timespec duration, rem;

    duration.tv_sec = 0;
    duration.tv_nsec = 1e8;

    sr = nanosleep(&duration, &rem);
    if (sr == -1)
        terminate("nanosleep", exit_process);

    do {
        kill(pid, SIGINT);
        wr = waitpid(-1, &status, WNOHANG);
    } while (wr == 0);

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

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

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <command with parameters ...>\n", argv[0]);
        exit(1);
    }

    pid = launch_process(&argv[1]);
    iterate_process(pid);

    return 0;
}
