[英]Multiple Pipes In Ubuntu Linux C programming using dup2
誰能告訴我這是什么問題? 我收到“grep:c 不是文件或目錄”的錯誤。 如果對 1 pipe(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 引起的。
第一個參數是您希望執行的文件,第二個參數是一個以 null 結尾的字符串數組,表示文件的適當 arguments。
實際上,您在 shell 中運行grep grep c
c。您可以嘗試一下,看看會發生相同的效果。
請參閱手冊頁https://linux.die.net/man/3/execvp以進一步閱讀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.