title: Implementing shell in C and need help handling input/output redirection
body: <h3>Round 2</h3>
  
  <p>After reading some of the answers, my revised code is:</p>
  
  <pre><code>int pid = fork();
  
  if (pid == -1) {
      perror("fork");
  } else if (pid == 0) {   
  
      if (in) { //if '&lt;' char was found in string inputted by user
          int fd0 = open(input, O_RDONLY, 0);
          dup2(fd0, STDIN_FILENO);
          close(fd0);
          in = 0;
      }
  
      if (out) { //if '&gt;' was found in string inputted by user
          int fd1 = creat(output, 0644);
          dup2(fd1, STDOUT_FILENO);
          close(fd1);
          out = 0;
      }   
  
      execvp(res[0], res);
      perror("execvp");
      _exit(1);
  } else {
      waitpid(pid, 0, 0);
      free(res);
  }
  </code></pre>
  
  <p>It works, but seems the standard output isn't being reconnected or something to that effect. Here is execution: </p>
  
  <pre><code>SHELL$ cat &gt; file
  hello, world
  this is a test
  SHELL$ cat &lt; file //no output
  SHELL$ ls //no output
  </code></pre>
  
  <p>'&lt;' and '>' both work, but after they are executed there is no output. </p>
  
  <hr>
  
  <h3>Round 1</h3>
  
  <p>I have been working on a relatively simple shell in C for a while now, but I am having trouble implementing input (&lt;) and output (>) redirection. Help me find the issues in the following code: </p>
  
  <pre><code>int fd;
  int pid = fork();
  int current_out;
  
  if (in) { //if '&lt;' char was found in string inputted by user
      fd = open(input, O_RDONLY, 0);
      dup2(fd, STDIN_FILENO);
      in = 0;
      current_out = dup(0);
  }
  
  if (out) { //if '&gt;' was found in string inputted by user
      fd = creat(output, 0644);
      dup2(fd, STDOUT_FILENO);
      out = 0;
      current_out = dup(1);
  }
  
  if (pid == -1) {
      perror("fork");
  } else if (pid == 0) {       
      execvp(res[0], res);
      perror("execvp");
      _exit(1);
  } else {
      waitpid(pid, 0, 0);
      dup2(current_out, 1);
      free(res);
  }
  </code></pre>
  
  <p>I may have some unnecessary material in there because I have been trying different things to get it to work. I am not sure what is going wrong. </p>