title: using dup2 and pipe to redirect stdin
body: <p>I have a program A that takes two arguments from stdin and exits with a unique code depending on the arguments. I am writing a program B that calls program A using fork and exec and let program B print out the code program A exits with. For some reason, program A doesn't seem to be getting the data I piped through to it in the child process of fork. I'm not sure if I'm piping the correct data to the child process. </p>
  
  <p>Could someone help me please? Thanks!</p>
  
  <p>Here is my code: </p>
  
  <pre><code>int program_B(void) {
  char var_a[256];
  char var_b[256];
  int fd[2];
  
   // Read from stdin 
  char *sendarray[2];
  sendarray[0] = var_a;
  sendarray[1] = var_b;
  
  
  if(fgets(var_a, MAXLINE, stdin) == NULL) {
      perror("fgets");
      exit(1);
  }
  
  if(fgets(var_b, MAXLINE, stdin) == NULL) {
      perror("fgets");
      exit(1);
  }
  
  if (pipe(fd) == -1) {
    perror("pipe");
    exit(1);
  }
  
  int pid = fork();
  
  // Child process -- error seems to be here. 
  if (pid == 0) {
  
      close(fd[1]);
  
      dup2(fd[0], fileno(stdin));
  
      close(fd[0]);
  
      execl("program_A", NULL);
  
      perror("exec"); 
      exit(1);
  
  } else {
  
      close(fd[0]);
      write(fd[1], sendarray, 2*sizeof(char*));
      close (fd[1]);
  
      int status; 
  
        if (wait(&amp;status) != -1) {
  
          if (WIFEXITED(status)) {
  
  
              printf("%d\n", WEXITSTATUS(status));
  
  
          } else {
            perror("wait");
            exit(1);
          }
        }
  
  
  }
  
  
  
  
  
  
  
  return 0;
  }
  </code></pre>