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

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

int main()
{
    int fd1[2], fd2[2], pid;

    pipe(fd1);
    pipe(fd2);

    pid = fork();
    if (pid == -1)
        terminate("fork", exit_process);
    if (pid == 0) {
        close(fd1[0]);
        dup2(fd1[1], 1);
        close(fd1[1]);

        close(fd2[0]);
        close(fd2[1]);

        execlp("ls", "ls", "-lR", NULL);
        terminate_exec("ls", exit_process);
    }

    pid = fork();
    if (pid == -1)
        terminate("fork", exit_process);
    if (pid == 0) {
        close(fd1[1]);
        dup2(fd1[0], 0);
        close(fd1[0]);

        close(fd2[0]);
        dup2(fd2[1], 1);
        close(fd2[1]);

        execlp("grep", "grep", "^d", NULL);
        terminate_exec("grep", exit_process);
    }

    pid = fork();
    if (pid == -1)
        terminate("fork", exit_process);
    if (pid == 0) {
        close(fd1[0]);
        close(fd1[1]);

        close(fd2[1]);
        dup2(fd2[0], 0);
        close(fd2[0]);

        execlp("wc", "wc", "-l", NULL);
        terminate_exec("grep", exit_process);
    }

    close(fd1[0]);
    close(fd1[1]);
    close(fd2[0]);
    close(fd2[1]);
    wait_process();
    wait_process();
    wait_process();

    return 0;
}
