gpt4 book ai didi

在 C 中编写多个管道

转载 作者:太空狗 更新时间:2023-10-29 17:19:16 40 4
gpt4 key购买 nike

我正尝试在 C 中为我的 shell 实现一个多管道。

我所拥有的只是一个管道函数,它通过管道传递一个 | b 但不是 |乙 | c.

int   c[2];
int returnv;
pid_t id;

pipe(c);
pid = fork()) == 0
if (pid)
{
dup2(c[1], 0);
close(p[1]);
close(p[1]);
execvp(array(0), array);
}

if ((pid = fork()) == 0)
{
dup2(p[0], 1);
close(p(0));
close(p[0]);
returnv = execvp(array[0], array);
}

close(p[1]);
wait(NULL);
wait(NULL);
wait(NULL);
return returnv;

这是第二个版本:

int i = 0;

while (i < x)

{
pipe(c);
if ((pid = fork()) == 0)
{
dup2(t[i], 1);
if (i < 2)
dup2(p[0], 1);
close(p[1]);
r= execvp(cmd[i][0], cmd[i]);
}
wait(NULL);
close(p[0]);
i += 1;
t[i] = p[1];

请问我如何添加一些小东西来使这段代码管理多个管道?非常感谢!

最佳答案

编辑:根据您的评论

要执行多个管道,您需要将所有命令存储在某处。这就是我使用结构选项卡的原因。

查看这个新版本可能更容易理解

所以首先你需要一个选项卡或其他东西来存储你所有的命令:

int main()
{
char *ls[] = {"ls", NULL};
char *grep[] = {"grep", "pipe", NULL};
char *wc[] = {"wc", NULL};
char **cmd[] = {ls, grep, wc, NULL};

loop_pipe(cmd);
return (0);
}

然后将运行选项卡并启动所有内容的函数

void    loop_pipe(char ***cmd) 
{
int p[2];
pid_t pid;
int fd_in = 0;

while (*cmd != NULL)
{
pipe(p);
if ((pid = fork()) == -1)
{
exit(EXIT_FAILURE);
}
else if (pid == 0)
{
dup2(fd_in, 0); //change the input according to the old one
if (*(cmd + 1) != NULL)
dup2(p[1], 1);
close(p[0]);
execvp((*cmd)[0], *cmd);
exit(EXIT_FAILURE);
}
else
{
wait(NULL);
close(p[1]);
fd_in = p[0]; //save the input for the next command
cmd++;
}
}
}

关于在 C 中编写多个管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17630247/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com