- 论坛徽章:
- 0
|
本帖最后由 buzzerrookie 于 2012-03-05 23:36 编辑
我想用C语言实现一下 ls -l | more | wc,写的代码如下,但没有输出,不知道哪里错了,请各位帮帮忙,谢谢各位。
- #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;
- }
复制代码 |
|