日期:2014-05-16 浏览次数:20831 次
#include <stdio.h> #include <unistd.h> #include <sys/wait.h> int main() { pid_t pid[3]; int pipe_fd[2]; int pipe_fd2[2]; int status; char *prog1[3] = {"/bin/ls", "-l", NULL}; char *prog2[2] = {"/bin/more", NULL}; char *prog3[2] = {"/usr/bin/wc", NULL}; if(pipe(pipe_fd) < 0){ perror("pipe 1 failed"); } if(pipe(pipe_fd2) < 0){ perror("pipe 2 failed"); } if((pid[0] = fork()) < 0){ perror("fork failed"); } if(pid[0] == 0){ close(pipe_fd[0]); dup2(pipe_fd[1], 1); close(pipe_fd[1]); execvp(prog1[0], prog1); } if(pid[0] > 0){ pid[1] = fork(); if(pid[1] == 0){ close(pipe_fd[1]); dup2(pipe_fd[0], 0); close(pipe_fd[0]); close(pipe_fd2[0]); dup2(pipe_fd2[1], 1); close(pipe_fd2[1]); execvp(prog2[0], prog2); } if(pid[1]>0){ pid[2] = fork(); if(pid[2] == 0){ close(pipe_fd2[1]); dup2(pipe_fd2[0], 0); close(pipe_fd2[0]); execvp(prog3[0], prog3); } } close(pipe_fd[0]); close(pipe_fd[1]); close(pipe_fd2[0]); close(pipe_fd2[1]); waitpid(pid[1], &status, 0); } return 0; }