title: C: `write error: Bad file descriptor` after fork, dup2, and execv
body: <p>Continuing on <a href="https://stackoverflow.com/questions/5268583/c-dup2-before-execv">this problem</a>, but I'll reiterate: </p>
  
  <p>For a homework assignment I have to write a basic shell including redirection. The program uses readline to prompt for input, parses the input string, and breaks it down into the executable name, the arguments, and the input/output file(s), if applicable. After parsing the string, it forks and the child execv()'s to the executable that was passed in. I'm using dup2() to change the file descriptors after the fork and before the execv, but am having a problem once the program has execv'd to the new executable. If in my shell I run <code>ls &gt; foo.out</code>, I get: <code>ls: write error: Bad file descriptor</code></p>
  
  <p>Here is the code for my child process (this is after fork()):</p>
  
  <pre><code>int _child(struct command *c){
      int ret;
      /* When given `ls &gt; foo.out`, these next two lines output:
      ** c-&gt;infile is (null)
      ** c-&gt;outfile is foo.out
      */
      printf("c-&gt;infile is %s\n",c-&gt;infile);
      printf("c-&gt;outfile is %s\n",c-&gt;outfile);
      if(c-&gt;infile){
          int fd = open( c-&gt;infile, O_RDONLY);
          int _fd_dup = dup2(fd,0);
          close(0);
          if(_fd_dup != 0){
              fprintf(stderr, "Failed to redirect command input.\n");
              return 0;
          }
      }
      if(c-&gt;outfile){
          int fd = open( c-&gt;outfile, O_WRONLY | O_CREAT | O_TRUNC, 0600);
          int _fd_dup = dup2(fd,1);
          close(1);
          if(_fd_dup != 1){
              fprintf(stderr, "Failed to redirect command output.\n");
              return 0;
          }
      }
  </code></pre>
  
  <p>I do not get the "Failed to redirect command output." error. As I mentioned, this is a homework assignment so I'm not looking for anyone to fix this, but rather point me in the right direction.</p>