Skip to content

Instantly share code, notes, and snippets.

@farhaven
Created August 17, 2014 15:33
Show Gist options
  • Save farhaven/31bf8f991167a9d7451e to your computer and use it in GitHub Desktop.
Save farhaven/31bf8f991167a9d7451e to your computer and use it in GitHub Desktop.
#include <err.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
int
main(void) {
int p[2], status;
pid_t child;
char *argv[2] = { "/usr/bin/wc", NULL };
if (pipe(p) < 0) {
err(errno, "pipe");
}
if ((child = fork()) < 0) {
err(errno, "fork");
}
if (child) {
close(p[1]);
if (dup2(p[0], STDIN_FILENO) < 0) {
err(errno, "dup2");
}
if (execv(argv[0], argv) < 0) {
err(errno, "execv");
}
} else {
close(p[0]);
/* Here, you'd read from stdin, filter, then write to p[1] */
if (write(p[1], "foo\n", 4) < 0) {
err(errno, "write");
}
wait(&status);
fprintf(stderr, "child exited with status %d\n", status);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment