我正在研究一个外壳(是的,这是一项任务,所以我不是在寻找解决方案,更多的是关于我做错了什么的指南和线索),而且我被管道卡住了。我已经阅读了许多教程,男人等等,甚至复制粘贴了一些“有效”的代码,似乎没有任何效果。
这是我到目前为止所拥有的:
void ft_run_pipe(char **cmd, int num)
{
int i;
int j;
int piped[num][2];
pid_t pid;
i = 0;
j = 0;
while (i < num)
{
ft_putstr("Creating pipe");
ft_putnbr(i);
ft_putchar('\n');
if (pipe(piped[i]) < 0)
ft_putstrn("piped failed");
i++;
}
while (cmd[j] != '\0')
{
pid = fork();
if (pid == 0)
{
ft_putchar('a');
if (j != 0)
{
ft_putstrn("If not first");
ft_putnbr(j - 1);
if (dup2(piped[j - 1][0], 0) < 0)
{
ft_putstrn("dup1 failed");
ft_putstrn(strerror(errno));
}
close(piped[j - 1][1]);
close(piped[j - 1][0]);
}
if (j != num)
{
ft_putstrn("If not last");
ft_putnbr(j);
if (dup2(piped[j][1], 1) < 0)
{
ft_putstrn("dup2i failed");
ft_putstrn(strerror(errno));
}
close (piped[j][0]);
close (piped[j][0]);
}
i = 0;
while (i < num)
{
close(piped[i][0]);
close(piped[i][1]);
i++;
}
// ft_run_special(cmd[j], environ);
}
else
{
i = 0;
while (i < num)
{
close(piped[i][0]);
close(piped[i][1]);
i++;
}
}
j++;
}
wait (NULL);
}
我编写了各种 ft_something 函数来替代一些 libc 函数(ft_putstr 写入一个字符串,最后用 n 添加一个 \n 等)。ft_exec_special 是一个使用 execve 执行可执行文件的函数,在 PATH 变量中进行搜索。
当使用两个命令和一个管道运行时,它返回
Creating pipe0
aIf not last
0aIf not first
0dup1 failed
Bad file descriptor
虽然在我看来,通常情况下,它应该可以工作 - piped[0][0] 存在,被正确地通过管道传输,并且某些内容被写入 piped[0][1] - 为什么它会说 piped[0][0]是一个坏的文件描述符?