Created
January 30, 2021 14:16
Revisions
-
rexim created this gist
Jan 30, 2021 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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; }