/* gcc -Wall -std=c99 open_pipe_command.c && ./a.out */ #include #include #include #include #include #include #define HELLO "hello world!" // 12 int open_pipe_command(int * fd, char * cmd, char **argv) { int pr[2]; pipe(pr); int pw[2]; pipe(pw); /* user reads in fd[0]=pr[0] & writes in fd[1]=pw[1] */ fd[0] = pr[0]; fd[1] = pw[1]; int pid = fork(); if(pid == 0) { /* child */ close(pw[1]); close(pr[0]); /* useless */ /* cmd writes in pr[1]=1 & reads in pw[0]=0 */ dup2(pw[0],0); dup2(pr[1],1); close(pw[0]); close(pr[1]); execvp(cmd, argv); perror("Error execvp"); exit(EXIT_FAILURE); } close(pw[0]); close(pr[1]); /* useless */ return pid; /* success > 0*/ } int main(int argc, char * argv[]) { int fd[2]; char* cmd[] = {"tr", "a-z", "A-Z", NULL}; int pid = open_pipe_command(fd, *cmd, cmd); if(pid <= 0) return EXIT_FAILURE; write(fd[1], HELLO, strlen(HELLO)+1); close(fd[1]); char msg[128]; int r = read(fd[0], msg, 128); printf("msg[%d]: %s -> %s\n", r, HELLO, msg); close(fd[0]); waitpid(pid, NULL, 0); return EXIT_SUCCESS; }