#include #include #include #include #include int main(int argc, char *argv[]) { if(argc < 2) { printf("Please provide at least one command to run\n"); exit(1); } int c2p[2]; if(-1 == pipe(c2p)) { perror("Error creating child to parent pipe"); exit(1); } int f = fork(); if(0 > f) { perror("Cannot create child process"); exit(1); } else if (0 == f) { close(c2p[0]); int sout = fileno(stdout); int backup = dup(sout); if(-1 == dup2(sout, c2p[1])) { perror("Cannot redirect stdout to pipe"); exit(1); } if(-1 == execvp(argv[1], argv+1)) { perror("Error on execvp"); exit(1); } if(-1 == dup2(sout, backup)){ perror("Cannot restore stdout"); exit(1); } close(c2p[1]); exit(0); } else { close(c2p[1]); int k = 0; char *buf = malloc(sizeof(char) * 101); while(0 != (k = read(c2p[0], buf, 100 * sizeof(char)))) { if(-1 == k) { perror("Error reading from pipe"); break; } buf[k] = 0; printf("%s", buf); } free(buf); close(c2p[0]); wait(NULL); } return 0; }