谁能告诉我这是什么问题?我收到一个错误
“grep:c 不是文件或目录”。如果对 1 个管道(2 个命令)执行相同的模式,它会完美运行,但是,如果我使用 2 个管道(3 个命令)执行此操作,它将停止工作。
谁能告诉我这段代码有什么问题?
int main(int argc, char** argv)
{
int pipefd[2];
int pipefd2[2];
char* cmd[3]={"ls",NULL,NULL};
char* cmd2[3]={"grep","c",NULL};
char* cmd3[3]={"wc", NULL, NULL};
pipe(pipefd);
pipe(pipefd2);
if(fork() == 0)
{
if(dup2(pipefd[1],1) < 0)
{
printf("Error in dup2\n");
exit(0);
}
close(pipefd2[0]);
close(pipefd2[1]);
close(pipefd[0]);
close(pipefd[1]);
if(execvp("ls", cmd) < 0)
{
printf("Error in execvp ls\n");
exit(0);
}
}
if(fork() == 0)
{
if(dup2(pipefd[0],0) < 0)
{
printf("Error in dup2\n");
exit(0);
}
if(dup2(pipefd2[1], 1) < 0)
{
printf("Error in dup2\n");
exit(0);
}
close(pipefd2[0]);
close(pipefd2[1]);
close(pipefd[0]);
close(pipefd[1]);
if(execvp("grep",cmd2) < 0)
{
printf("Error in execvp grep\n");
exit(0);
}
}
if(fork() == 0)
{
if(dup2(pipefd2[0],0) < 0)
{
printf("Error in dup2\n");
exit(0);
}
close(pipefd2[0]);
close(pipefd2[1]);
close(pipefd[0]);
close(pipefd[1]);
if(execvp("wc",cmd2) < 0)
{
printf("Error in execvp wc\n");
exit(0);
}
}
close(pipefd[0]);
close(pipefd[1]);
close(pipefd2[0]);
close(pipefd2[1]);
wait(NULL);
wait(NULL);
wait(NULL);
return 0;
}
最佳答案
这是由于不正确使用 execvp 造成的。
The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file.
实际上,您正在运行
grep grep c
在你的壳里。您可以尝试一下,看看是否会发生相同的效果。参见手册页 https://linux.die.net/man/3/execvp供进一步阅读。
关于linux - 使用 dup2 的 Ubuntu Linux C 编程中的多个管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69329415/