Home > Blockchain >  Am I piping correctly?
Am I piping correctly?

Time:10-10

For my piping function, I am creating two child processes with fork() and attempting to pipe the contents of the first over to the second child process before calling execvp(). I am doing something wrong, as if I do ls -la | more, the output is a vertical list of the files in the directory. I am very new to piping in c (and c) so chances are that it is an overlooked mistake. Any help is appreciated!

void handle_pipe_cmds(char **args1, char **args2){
    char ** word1 = parse_space(*args1);
    char ** word2 = parse_space(*args2);

    int p[2];
    pipe(p);
    pid_t pid = fork();
    if (pid == -1) {
        printf("CANNOT FORK!");
    } else if (pid == 0) {
        dup2(p[1], STDOUT_FILENO);
        close(p[1]);
        int status = execvp(word1[0], word1);
        if (status != 0) {
            printf("%s failed\n", word1[0]);
            exit(1);
        }
        exit(0);
    } else {
        close(p[1]);
        wait(NULL);
    }

    pid = fork();
    if (pid == -1) {
        printf("CANNOT FORK!");
    } else if (pid == 0) {
        dup2(p[0], STDIN_FILENO);
        close(p[1]);
        close(p[0]);
        int status = execvp(word2[0], word2);
        if (status != 0) {
            printf("%s failed\n", word2[0]);
            exit(1);
        }
        exit(0);
    } else {
        close(p[1]);
        close(p[0]);
        wait(NULL);
    }

}

CodePudding user response:

If I do ls -la | more, the output is a vertical list of the files in the directory.

That is because the ls program is aware of whether its output stream is a terminal or not, and acts different in both cases. On a terminal, it (may) print colorized entries, and multiple items per line; to a pipe, or a file, it will print just one entry per line with no color. See man ls for details.

  • Related