Created
October 26, 2011 23:31
-
-
Save basicer/1318333 to your computer and use it in GitHub Desktop.
This file contains 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 characters
#include <stdio.h> | |
#include <unistd.h> | |
#define PERROR_AND_DIE(_x_) {perror(_x_); _exit(1);} | |
int main(int argc, char **argv) { | |
int fd0[2]; | |
int fd1[2]; | |
if ( argc != 3 ) { | |
fprintf(stdout, "Usage %s: \"[command 1]\" \"[command 2]\"\n", argv[0]); | |
_exit(1); | |
} | |
if ( pipe(fd0) || pipe(fd1) ) PERROR_AND_DIE("pipe") | |
pid_t id = fork(); | |
if ( id == -1 ) PERROR_AND_DIE("fork"); | |
if ( id ) { | |
if ( -1 == close(0) ) PERROR_AND_DIE("P1: close 0"); | |
if ( -1 == dup2(fd0[0], 0) ) PERROR_AND_DIE("P1: dup 0"); //Read my STDIN from this pipe | |
if ( -1 == close(1) ) PERROR_AND_DIE("P1: close 1"); | |
if ( -1 == dup2(fd1[1], 1) ) PERROR_AND_DIE("P1: dup 1"); //Write my STDOUT here | |
execl("/bin/sh", "/bin/sh", "-c", argv[1], NULL); | |
PERROR_AND_DIE("P1: exec") | |
} | |
if ( -1 == close(0) ) PERROR_AND_DIE("P2: close 0"); | |
if ( -1 == dup2(fd1[0], 0) ) PERROR_AND_DIE("P2: dup 0"); | |
if ( -1 == close(1) ) PERROR_AND_DIE("P2: close 1"); | |
if ( -1 == dup2(fd0[1], 1) ) PERROR_AND_DIE("P2: dup 1"); | |
execl("/bin/sh", "/bin/sh", "-c", argv[2], NULL); | |
PERROR_AND_DIE("P2: exec") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment