Skip to content

Instantly share code, notes, and snippets.

@rexim
Created January 30, 2021 14:16
Show Gist options
  • Save rexim/b263598fd2ab3070c7363984bde79a17 to your computer and use it in GitHub Desktop.
Save rexim/b263598fd2ab3070c7363984bde79a17 to your computer and use it in GitHub Desktop.
Piping two commands together on POSIX
#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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment