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

enum { processes_limit = 64, cmds_limit = 64 };

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

typedef int (*fds_t)[2];

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

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

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

    wr = wait(&status);
    if (wr == -1)
        terminate("wait", 1);
    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));
}

void close_in_out(fds_t fds, int i)
{
    close(fds[i][0]);
    close(fds[i][1]);
}

void launch_process_pipe(char *const cmd[], fds_t fds, int i, int n)
{
    int pid;

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

        if (i > 0) {
            close(fds[i-1][1]);
            dup2(fds[i-1][0], 0);
            close(fds[i-1][0]);
        }

        if (i < n - 1) {
            close(fds[i][0]);
            dup2(fds[i][1], 1);
            close(fds[i][1]);
        }

        execvp(cmd[0], cmd);
        terminate_exec(cmd[0], exit_process);
    }
}

int main()
{
    int i, n, fds[processes_limit][2];
    char *cmds[cmds_limit];

    n = 4;

    pipe(fds[0]);
    cmds[0] = "ls"; cmds[1] = "-lR"; cmds[2] = NULL;
    launch_process_pipe(cmds, fds, 0, n);

    pipe(fds[1]);
    cmds[0] = "grep"; cmds[1] = "^d"; cmds[2] = NULL;
    launch_process_pipe(cmds, fds, 1, n);
    close_in_out(fds, 0);

    pipe(fds[2]);
    cmds[0] = "cat"; cmds[1] = NULL;
    launch_process_pipe(cmds, fds, 2, n);
    close_in_out(fds, 1);

    cmds[0] = "wc"; cmds[1] = "-l"; cmds[2] = NULL;
    launch_process_pipe(cmds, fds, 3, n);
    close_in_out(fds, 2);

    for (i = 0; i < n; i++)
        wait_process();

    return 0;
}
