gpt4 book ai didi

c - 使用简单的unix管道

转载 作者:行者123 更新时间:2023-11-30 15:26:54 26 4
gpt4 key购买 nike

出于某种原因,我无法正确处理,我想通过管道调用“ls -l”和“tail -n 2”,以便显示文件列表中的最后两个文件。这是代码:

int pipefd[2];
pipe(pipefd);
int id = fork();

if(id == 0)
{
dup2(pipefd[1], 1);
close(pipefd[1]);
execvp("ls", (char*[]){"ls", "-l", NULL});
}
else
{
dup2(pipefd[0], 0);
execvp("tail", (char*[]){"tail", "-n", "2", NULL});
waitpid(id, NULL, 0);
close(pipefd[0]);
}

return 0;

下面的代码有什么问题?我感觉我这里有一个误区,我也查了很多,网上也没有找到答案...

最佳答案

通过调用:

dup2(pipefd[1], 1);
关闭(pipefd[1]);

在子进程中,您正在关闭已经关闭的pipefd[1],因此close(pipefd[1]);无效。您还应该关闭子进程中的pipefd[0]。这同样适用于父进程。因此,您的代码应按如下方式编辑:

int pipefd[2];
pipe(pipefd);
int id = fork();

if(id == 0)
{
dup2(pipefd[1], 1);
close(pipefd[0]);
execvp("ls", (char*[]){"ls", "-l", NULL});
}
else
{
dup2(pipefd[0], 0);
close(pipefd[1]);
execvp("tail", (char*[]){"tail", "-n", "2", NULL});
waitpid(id, NULL, 0);
}

关于c - 使用简单的unix管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27257864/

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