title: Creating a Linux pipe using C++
body: <p>I am trying to create a simple shell program that includes pipes and redirects. For piping I currently have the following code:</p>
  
  <pre><code>//****Contains Prompts for User Input outside of 'If' statement********
  
  if( contains(userInput, '|', str1, str2));
  
  //Fork a child process
  pid_t pid1 = fork();
  if (pid1 == 0) {
  
  //First child creates the pipe
  pipe(pipeFD);
  
      //First child forks to a second child
      pid_t pid2 = fork();
      if(pid2 == 0){
  
      //Replaces standard output with pipe input
      dup2(pipeFD[1], 1);
  
  
      //Executes first command
      parseArgs(str1, argv);
      execvp(argv[0],argv);
      }else{wait(NULL);}
  
  //Back in first child
  
      //Fork a third child
      pid_t pid3 = fork();
      if(pid3 == 0){
  
      //Third child replaces standard input with pipe output
      dup2(pipeFD[0],0);
  
      //Third child executes the second command
      parseArgs(str2, argv);
      execvp(argv[0],argv);
      exit(EXIT_FAILURE);
      }else{wait(NULL);}
  
    }
  }
  </code></pre>
  
  <p>As it stands right now, I've been using ls|grep as a test for my pipe. The output should look like this:</p>
  
  <pre><code>ls|grep hello
  hello.cpp
  helloworld.cpp
  helloworld2.cpp
  Enter a command:
  </code></pre>
  
  <p>instead, it looks like this:</p>
  
  <pre><code>ls|grep hello
  Enter a command: hello.cpp
  helloworld.cpp
  helloworld2.cpp
  </code></pre>