我试图编写一个程序,它将产生任意数量的子进程,并在它们之间进行管道传输,就像命令行管道一样。在我的情况下,我正在尝试执行 "ls -l | more" 并将其输出到 stdout,然后使父进程继续执行更多的命令。
以下是我作为最小示例的代码:
int main (int argc, const char * argv[]) {
int fd[2];
pipe(fd);
chdir("/directory/with/lots/of/files");
// Create one child process for more
int pid = fork();
if (pid == 0) {
close(fd[1]);
int ret = dup2(fd[0],0);
if (ret < 0) perror("dup2");
char *argv[10];
argv[0] = "more"; argv[1] = NULL;
execvp("more", argv);
}
// Create another child process for ls
int pid2 = fork();
if (pid2 == 0) {
int ret = dup2(fd[1],1);
if (ret < 0) perror("dup2");
char *argv[10];
argv[0] = "ls"; argv[1] = "-l";
argv[2] = NULL;
execvp("ls", argv);
}
// wait for the more process to finish
int status;
waitpid(pid, &status, 0);
printf("Done!\n");
return 0;
}
现在,当我执行程序(当然是在一个main()函数中)时,得到的输出比较多,这是预期的。我按下“d”翻页,按下“u”向上滚动,它似乎运行良好。但是当我到达底部时,它不像more那样退出,而是留下一行空白。Ctrl-C可以退出,但它会退出整个程序,意味着“Done!”行永远不会被打印。这里有一部电影(链接已失效)说明了发生了什么(请注意,在最后我按下Ctrl-C返回到bash)。
对此您有什么想法吗?我只是想弄清楚如何改变它,使得当more到达底部时,它会退出并返回到父进程,以便它可以继续执行。
more
是否是指向less
的符号链接。Less需要使用-e
选项在文件末尾退出。您的程序环境中的PATH
与交互式环境可能存在差异。 - Dennis Williamson