OneCompiler

slip14

148

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>

void signalHandler(int signal) {
}

int main() {
signal(SIGINT, signalHandler);
signal(SIGQUIT, signalHandler);

int pipefd[2];
if (pipe(pipefd) == -1) {
    perror("pipe");
    return 1;
}

pid_t lsPid = fork();
if (lsPid == -1) {
    perror("fork");
    return 1;
} else if (lsPid == 0) {

    close(pipefd[0]);

    if (dup2(pipefd[1], STDOUT_FILENO) == -1) {
        perror("dup2");
        return 1;
    }

    close(pipefd[1]);

    execlp("ls", "ls", "-l", NULL);
    perror("execlp");
    return 1;
}

pid_t wcPid = fork();
if (wcPid == -1) {
    perror("fork");
    return 1;
} else if (wcPid == 0) {

    close(pipefd[1]);

    if (dup2(pipefd[0], STDIN_FILENO) == -1) {
        perror("dup2");
        return 1;
    }

    close(pipefd[0]);

    execlp("wc", "wc", "-l", NULL);
    perror("execlp");
    return 1;
}

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

if (waitpid(lsPid, NULL, 0) == -1) {
    perror("waitpid");
    return 1;
}

if (waitpid(wcPid, NULL, 0) == -1) {
    perror("waitpid");
    return 1;
}

return 0;

}