- 论坛徽章:
- 0
|
帮顶,如果只是1个管道的话,ls|more没问题,但2个管道就在more处阻塞了.希望高人指点下.- #include <stdio.h>
- #include <unistd.h>
- #include <sys/wait.h>
- #include <sys/types.h>
- #include <cstdlib>
- #include <iostream>
- using namespace std;
- int isready(int fd)
- {
- int rc;
- fd_set fds;
- struct timeval tv;
- FD_ZERO(&fds);
- FD_SET(fd, &fds);
- tv.tv_sec = 1;
- tv.tv_usec = 0;
- rc = select(fd + 1, &fds, NULL, NULL, &tv);
- if (rc < 0) //error
- return -1;
- return FD_ISSET(fd, &fds) ? 1 : 0;
- }
- int main()
- {
- pid_t pids[10];
- int pipes[10][2];
- char *ls[] =
- { "ls", NULL };
- char *more[] =
- { "more", NULL };
- char *wc[] =
- { "wc", NULL };
- int i, status;
- for (i = 0; i < 10; i++)
- {
- if (pipe(pipes[i]) == -1)
- {
- printf("pipe error\n");
- }
- }
- if ((pids[0] = fork()) == -1)
- {
- perror("fork error");
- }
- else if (pids[0] == 0)
- {
- //输出
- close(pipes[0][0]);
- close(STDOUT_FILENO);
- dup2(pipes[0][1], STDOUT_FILENO);
- close(pipes[0][1]);
- if (execvp(ls[0], ls) == -1)
- {
- printf("exec %s failed\n", ls[0]);
- }
- }
- else if (pids[0] > 0)
- {
- wait(NULL);
- if ((pids[2] = fork()) == -1)
- {
- perror("fork error");
- }
- else if (pids[2] == 0)
- {
- //输入
- //sleep(2);
- if (isready(pipes[0][0]) > 0)
- {
- cout << "ready" << endl;
- close(pipes[0][1]);
- close(STDIN_FILENO);
- dup2(pipes[0][0], STDIN_FILENO);
- close(pipes[0][0]);
- //输出
- close(pipes[1][0]);
- close(STDOUT_FILENO);
- dup2(pipes[1][1], STDOUT_FILENO);
- dup2(pipes[1][1], STDERR_FILENO);
- close(pipes[1][1]);
- if (execvp(more[0], more) == -1)
- {
- printf("exec %s failed\n", more[0]);
- }
- }
- }
- else if (pids[2] > 0)
- {
- //输入
- wait(NULL);
- ////waitpid( pids[2], &status, 0 );
- if (isready(pipes[1][0]) > 0)
- {
- cout << "ready 2" << endl;
- close(pipes[1][1]);
- close(STDIN_FILENO);
- dup2(pipes[1][0], STDIN_FILENO);
- close(pipes[1][0]);
- if (execvp(wc[0], wc) == -1)
- {
- printf("exec %s failed\n", ls[0]);
- }
- }
- }
- }
- close(pipes[0][0]);
- close(pipes[0][1]);
- close(pipes[1][0]);
- close(pipes[1][1]);
- return 0;
- }
复制代码 |
|