我正在做自己的tcsh版本(用于家庭作业),当涉及到管道和重定向(现在是管道)时,我遇到了问题。
正如我所说,我尝试将程序的输出重定向到另一个程序的输入。我几乎正确地做到了,直到出现以下问题: 执行的第二个程序挂起并等待用户的输入,这不应发生。还有我的调试代码。 在哪里创建孩子:
static int generate_child(shell_t *shell, parsing_t *cmd, char *path, char **env)
{
pid_t child = 0;
printf("Child fds will be: %i & %i\n", cmd->fds[STDIN_FILENO], cmd->fds[STDOUT_FILENO]);
child = fork();
if (child == -1)
return (ERR_FORK);
if (child != 0)
wait_for_child(shell, cmd->args[0]);
else {
if (cmd->fds[STDIN_FILENO] > 0) {
dup2(cmd->fds[STDIN_FILENO], STDIN_FILENO);
printf("[#1] Closing fd: %i\n", cmd->fds[STDIN_FILENO]);
close(cmd->fds[STDIN_FILENO]);
}
if (cmd->fds[STDOUT_FILENO] != -1 && cmd->fds[STDIN_FILENO] != 1) {
dup2(cmd->fds[STDOUT_FILENO], STDOUT_FILENO);
printf("[#2] Closing fd: %i\n", cmd->fds[STDOUT_FILENO]);
close(cmd->fds[STDOUT_FILENO]);
}
execve(path, cmd->args, env);
display_perror(shell, cmd->args[0]);
_exit(ERR_CHILD);
}
return (ERR_NONE);
}
创建新的fds并将当前节点/ cmd与下一个链接。
int link_pipe(shell_t *shell, parsing_t *current)
{
int new_pipe[2];
if (pipe2(new_pipe, O_CLOEXEC))
return (ERR_PIPE);
current->piped[STDOUT_FILENO] = new_pipe[STDOUT_FILENO];
current->piped[STDIN_FILENO] = new_pipe[STDIN_FILENO];
printf("[Pipe] %s s' fds are: %i & %i\n", current->args[0], current->piped[STDIN_FILENO], current->piped[STDOUT_FILENO]);
if (current->fds[STDOUT_FILENO] == -1)
current->fds[STDOUT_FILENO] = current->piped[STDOUT_FILENO];
if (current->next != NULL)
current->next->fds[STDIN_FILENO] = current->piped[STDIN_FILENO];
return (ERR_NONE);
}
Aaand,所有命令均在其中执行:
static int affect_all_cmds(shell_t *shell)
{
parsing_t *current = shell->cmds;
int returned_val = ERR_NONE;
while (current != NULL) {
execute_alias(shell, ¤t->args);
returned_val = apply_linkers(shell, current); // link_pipe is used here
if (returned_val != ERR_NONE)
return (returned_val);
returned_val = redirect_cmds(shell, current); // generate_child is used here
if (returned_val != ERR_NONE)
return (returned_val);
current = current->next;
}
remove_all_queued_cmd(&shell->cmds); // Here are removed (from 'piped[...]') every fds open by 'pipe2'
return (returned_val);
}
我很可能确定我没有正确关闭某些东西,但是找不到。自一个星期以来,我尝试了很多事情,但没有任何效果。
另外,对于我的测试,我会做类似ls | grep c
的事情,而现在的结果是:
$ ls | grep c
ls -> 2 // Detecting a pipe
[Pipe] ls s fds are: 3 & 5 // Generating fds
Child fds will be: 0 & 5 // Running 'ls' with edited fds
grep -> 0 // No pipe or redirections detected
Child fds will be: 3 & -1 // Running 'grep'
[#1] Closing fd: 3
cmake-build-debug
include
main.c
src
然后挂起,直到我按CTRL + C。