title: Redirecting stdout to file after a fork()
body: <p>I'm working on a simple shell, but right now I am just trying to understand redirection. I'm just hard coding an ls command and trying to write it to a file for now. Currently, the ls runs, and the output file is created, but the output still goes to stdout and the file is blank. I'm confused as to why. Thanks in advance.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>int main()
  {
      int ls_pid; /* The new process id for ls*/
      char *const ls_params[] = {"/bin/ls", NULL}; /* for ls */
      int file; /* file for writing */
  
      /* Open file check user permissions */
      if (file = open("outfile", O_WRONLY|O_CREAT) == -1) /* , S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP */
      {
          perror("Failed to open file");
          _exit(EXIT_FAILURE);
      } 
  
      ls_pid = fork(); /* Create new process for ls */
  
      if (ls_pid == -1) /* error check */
      {
          perror("Error forking ls (pid == -1)");
          _exit(EXIT_FAILURE);
      }
      else if (ls_pid == 0) /* Child of ls */
      {
          /* Redirect output to file */
          if (dup2(file, STDOUT_FILENO) == -1) /* STDOUT_FILENO = 1 */
          {
              perror("Error duping to file");
              _exit(EXIT_FAILURE);
          }
          close(file);
  
          execvp("ls", ls_params); /* create the sort process */
          /* execlp("ls", "ls", NULL); */
  
          /* if this does not end the program, something is wrong */
          perror("Exec failed at sort");
          _exit(EXIT_FAILURE);
      }
      else /* ls parent (1) */
      {
          /* wait for child */
          if (wait(NULL) == -1)
          {
              perror("fork failed on parent");
              _exit(EXIT_FAILURE);
          }
      }
  
  }
  </code></pre>