/* File: ~liux/public_html/courses/cop4610/examples/simple-pipe-cmd.cc Purpose: Demonstrate how to use pipes to communicate between parent and child processes and use dup for I/O redirection Author: Xiuwen Liu, On the web: http://www.cs.fsu.edu/~liux/courses/cop4610/examples/simple-pipe-cmd.cc Compile: g++ -o simple-pipe-cmd simple-pipe-cmd.cc */ #include #include #include #include #include #include #include #define MAXLINE 512 int main(int argc, char *argv[]) { int n, fd[2]; pid_t pid[2]; char *my_argv[3]; int status; if (pipe(fd) < 0) { perror("pipe"); return -1; } if ( (pid[0] = fork()) < 0) { cerr << "Counld not create new process." << endl; perror("fork"); return -1; } else { if (pid[0] ==0) { /* Child */ close(0); dup(fd[0]); // Redict standard input fd[1] close(fd[0]); close(fd[1]); // Close unused open files if (argc ==3) { my_argv[0] = argv[2]; } else { my_argv[0]= "/bin/cat"; } my_argv[1] = (char *)NULL; if (execv(my_argv[0], my_argv) <0) { cerr << "Could not execute " << my_argv[0] << endl; exit(-1); } } else { /* Parent */ if ( (pid[1]= fork()) < 0) { cerr << "Counld not create new process." << endl; perror("fork"); return -1; } else { if (pid[1] ==0) { close(1); dup(fd[1]); // Redict standard output to fd[0] close(fd[0]); close(fd[1]); // Close unused open files if (argc >= 2 ) { my_argv[0]= argv[1]; my_argv[1] = (char *)NULL; } else { my_argv[0]= "/bin/ps"; my_argv[1] = "-e"; my_argv[2] = (char *)NULL; } if (execv(my_argv[0], my_argv) <0) { cerr << "Could not execute " << my_argv[0] << endl; exit(-1); } } } } } close(fd[0]); close(fd[1]); waitpid(pid[0], &status, 0); waitpid(pid[1], &status, 0); return 0; }