【发布时间】:2018-12-04 08:00:34
【问题描述】:
我知道这个主题已经发布了很多,但我希望将其引向不同的方向。我想编写一个具有 shell 管道功能的程序,即 cmd1 |命令2 | cmd3 管道和重定向。我已阅读 this、this 和 this 等页面以供参考。这些解决方案非常适合“水平流水线”,但我想“垂直”实现它。为了使我的外壳垂直,每个“命令”进程必须有一个不同的父进程(上一个命令)。因此,每个要执行的命令都是从前一个命令产生的。我遇到的问题是,当我在孩子中递归(而不是像示例中的父级)时,程序执行得很好,但随后挂起,我必须按回车键重新提示我的 shell。我很好奇为什么这是不同的以及如何解决这个问题。
static void exec_pipeline(size_t pos, int in_fd) {
// Invalid Pipe has issues
if (newargv[pipe_commands[pos+1]] == NULL)
report_error_and_exit("Invalid pipe");
/* last command, pipe_command conatins indices of commands to execute */
if (pipe_commands[pos + 1] == 0) {
redirect(in_fd, STDIN_FILENO); /* read from in_fd, write to STDOUT */
execvp(newargv[pipe_commands[pos]], newargv + pipe_commands[pos]);
report_error_and_exit("execvp last command");
}
else { /* $ <in_fd cmds[pos] >fd[1] | <fd[0] cmds[pos+1] ... */
int fd[2]; /* output pipe */
if (pipe(fd) == -1)
report_error_and_exit("pipe");
switch(fork()) {
case -1:
report_error_and_exit("fork");
case 0: /* parent: execute the rest of the commands */
CHK(close(fd[1])); /* unused */
CHK(close(in_fd)); /* unused */
exec_pipeline(pos + 1, fd[0]); /* execute the rest */
default: /* child: execute current command `cmds[pos]` */
child = 1;
CHK(close(fd[0])); /* unused */
redirect(in_fd, STDIN_FILENO); /* read from in_fd */
redirect(fd[1], STDOUT_FILENO); /* write to fd[1] */
execvp(newargv[pipe_commands[pos]], newargv + pipe_commands[pos]);
report_error_and_exit("execvp");
}
}
}
void report_error_and_exit(const char *msg) {
perror(msg);
(child ? _exit : exit)(EXIT_FAILURE);
}
/* move oldfd to newfd */
void redirect(int oldfd, int newfd) {
if (oldfd != newfd) {
if (dup2(oldfd, newfd) != -1)
CHK(close(oldfd));
else
report_error_and_exit("dup2");
}
}
CHK 很像 assert,定义在一个名为 CHK.h 的文件中,如果您好奇,它看起来像这样:
do {if((x) == -1)\
{fprintf(stderr,"In file %s, on line %d:\n",__FILE__,__LINE__);\
fprintf(stderr,"errno = %d\n",errno);\
perror("Exiting because");\
exit(1);\
}\
} while(0)
【问题讨论】:
-
更新:问题是我如何等待进程完成,我目前正在研究解决方案。
标签: c shell recursion pipe file-descriptor