linux - 使用 dup2 的 Ubuntu Linux C 编程中的多个管道

标签 linux ubuntu pipe dup2

谁能告诉我这是什么问题?我收到一个错误
“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/

相关文章:

php - 亚马逊 Linux PHP Mbstring

linux - 用于 Linux 的 NUMA 感知命名共享内存

python - 有没有办法用 Python 控制窗口?

linux - vim问题,我将其删除

linux - lsb_release : command not found in latest Ubuntu Docker container

python - 在 Windows 上使用命令 "sudo apt-get install openblas-dev"?

android - Python 的多处理管道不工作

子进程卡在管道内

java - IOException:读取结束死

linux - 我需要将文件中指定的模式列表与另一个文件进行比较,并仅报告包含模式的列的匹配部分