title: How can I exec and write to stdin and pipe stdout to a socket?
body: <p>I'm writing an http server for my school project, and I'm trying to execute a CGI script. The following code successfully executes the cgi program, and the output of the program is sent to the browser, but there's something wrong with the way I'm sending POSTed data. Here's what I've got:</p>
  
  <pre><code>    int p[2];
      pipe(p);
  
      int pid = fork();
  
      if (pid == 0) {
          close(p[1]);
  
          dup2(p[0], STDIN_FILENO);
          dup2(socket, STDOUT_FILENO);
  
          execve(path.c_str(), {}, (char**) &amp;env[0]);
      } else {
          close(p[0]);
  
          string body = req-&gt;getBody();
          write(p[1], body.c_str(), body.size());
  
          close(socket);
      }
  </code></pre>
  
  <p>If I understand CGI correctly I just need to set an HTTP_CONTENT_LENGTH environment variable (which I'm doing) and send the request body to stdin. Am I using pipe, dup2, and write the correct way to do that?</p>
  
  <p>When posting to my test PHP script, the $_POST array is empty. When posting to my test perl script, it simply never sends any response or finishes running; I assume it's waiting for more stdin. If there's nothing obviously wrong with my piping and dup2ing, I'll post some compilable test code that illustrates the problem.</p>
  
  <p>Thank you!</p>