我正在尝试分叉,然后在子进程中执行两个或多个管道命令。我的想法是使用 while 循环在一个进程中连续分叉并执行命令,同时在另一个进程中继续循环。这是我的代码:
void
execute_pipe_command(command_t *c)
{
command_t command = *c;
pid_t pid = fork();
if(pid > 0) {
int status;
while(waitpid(pid, &status, 0) < 0)
continue;
if(!WIFEXITED(status))
error(1, errno, "Child exit error");
command->status = WEXITSTATUS(status);
return;
} else if (pid == 0) {
while(command->type == PIPE_COMMAND)
{
int fd[2]; pipe(fd);
pid = fork();
if(pid > 0) {
close(fd[0]);
dup2(fd[1], STDOUT_FILENO);
char **args = command->u.command[1]->u.word;
execvp(args[0], args);
} else if (pid == 0) {
close(fd[1]);
dup2(fd[0], STDIN_FILENO);
command = command->u.command[0];
continue;
} else {
error(1, errno, "forking error");
}
}
char **args = command->u.word;
execvp(args[0], args);
} else {
error(1, errno, "forking error");
}
}
Command 是一个保存它的类型的结构,如果它是一个管道命令,它保存左右子命令。否则,如果它是一个简单的命令,它包含一个组成命令的字符串数组。
当我使用管道命令调用此函数时,ls | cat
它应该执行命令,但它的行为却很奇怪。前两个管道命令将运行,但不会将控制权交还给程序。相反,它会挂起。随后的命令将被忽略。所以如果我给出这个ls | cat | wc
函数将打印 ls 并且在我给出一个 SIGINT 之前不会退出。
我对发生了什么感到非常困惑。如果有人能指出问题,我将不胜感激。