简体   繁体   中英

Multiple Pipes In Ubuntu Linux C programming using dup2

Can anyone tell me what's the issue in this please? I am getting an error that "grep: c is not a file or directory". If do this same pattern for 1 pipe (2 commands), it works perfectly, However, if I do it with 2 pipes (3 commands), it stops working.

CAN ANYONE PLEASE TELL ME WHAT'S THE ISSUE IN THIS CODE?

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;
}

This is caused by incorrect use of 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.

Effectively, you are running grep grep c in your shell. You can try it, and see that the same effect happens.

See the man page https://linux.die.net/man/3/execvp for further reading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM