【发布时间】:2014-01-21 02:28:39
【问题描述】:
我想编写一个小程序,打印出一个长列表,可以通过more(或less)在终端中分页,以便可以从头到尾检查该列表脚趾...
程序:
-
fork是在其中执行more程序的子进程 - 在父进程中,打印列表
- 在父/子之间设置了
pipe,以便父打印到stdout的列表被发送到more程序的stdin
代码:
int main(int argc, char *argv[])
{
int pager, status;
int pipes[2];
pipe(pipes);
pager = fork();
if (pager == 0) { // child
dup2(pipes[0], 0);
close(pipes[1]);
char *args[] = {"more", NULL};
execvp(args[0], args);
} else { // parent
dup2(pipes[1], 1);
int x;
for (x = 0; x < 500; x++) {
printf("Hello World! %d\n", x);
}
close(pipes[0]);
close(pipes[1]);
wait(&status);
}
return 0;
}
我大部分时间都在工作:
- 一长串“Hello World!...”消息打印在终端上,由
--More--剪裁,因此我知道基本管道设置正在运行。 - 如果我在整个列表完成打印(退出
more进程)之前按[q],则程序(父/子)按预期退出
我遇到的唯一问题是,如果我一直按[space] 或[return](这会推进more 给出的输出)并到达我的列表末尾(第500 个“Hello World!... " message) 然后终端挂起。按[q] 没有反应(我必须[ctrl+c] 才能离开)。
父进程卡在wait。 more 进程没有退出,即使我已经关闭了父级中的两个管道
【问题讨论】: