Skip to content

Instantly share code, notes, and snippets.

@rexim
Created January 30, 2021 14:16

Revisions

  1. rexim created this gist Jan 30, 2021.
    63 changes: 63 additions & 0 deletions main.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,63 @@
    #include <assert.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <errno.h>

    #include <sys/types.h>
    #include <sys/wait.h>
    #include <sys/stat.h>
    #include <unistd.h>
    #include <fcntl.h>

    #define ERR(expr) \
    do { \
    int err = expr; \
    if (err < 0) { \
    fprintf(stderr, "%s: %s\n", #expr, strerror(errno)); \
    exit(1); \
    } \
    } while (0)

    int main(void)
    {
    // cat ./main.c | sort

    int pipefd[2] = {0};

    ERR(pipe(pipefd));

    pid_t cpid = fork();
    assert(cpid >= 0);

    if (cpid == 0) {
    int input = open(__FILE__, O_RDONLY);
    assert(input >= 0);

    ERR(close(pipefd[0]));
    ERR(dup2(input, STDIN_FILENO));
    ERR(dup2(pipefd[1], STDOUT_FILENO));
    ERR(execlp("cat", "cat", NULL));
    }

    cpid = fork();
    assert(cpid >= 0);

    if (cpid == 0) {
    int output = open("./output.txt", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
    assert(output >= 0);

    ERR(close(pipefd[1]));
    ERR(dup2(pipefd[0], STDIN_FILENO));
    ERR(dup2(output, STDOUT_FILENO));
    ERR(execlp("sort", "sort", NULL));
    }

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

    ERR(wait(NULL));
    ERR(wait(NULL));

    return 0;
    }