title: How to execute a command and get return code stdout and stderr of command in C++
body: <p>Given the following answer (first c++11 answer):</p>
  <p><a href="https://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c-using-posix">How do I execute a command and get the output of the command within C++ using POSIX?</a></p>
  <p>Here is the implementation for your convenience:</p>
  <pre><code>#include &lt;cstdio&gt;
  #include &lt;iostream&gt;
  #include &lt;memory&gt;
  #include &lt;stdexcept&gt;
  #include &lt;string&gt;
  #include &lt;array&gt;
  
  std::string exec(const char* cmd) {
      std::array&lt;char, 128&gt; buffer;
      std::string result;
      std::shared_ptr&lt;FILE&gt; pipe(popen(cmd, &quot;r&quot;), pclose);
      if (!pipe) throw std::runtime_error(&quot;popen() failed!&quot;);
      while (!feof(pipe.get())) {
          if (fgets(buffer.data(), 128, pipe.get()) != nullptr)
              result += buffer.data();
      }
      return result;
  }
  </code></pre>
  <p>This works really nicely to execute a command (e.g. <code>std::string res = exec(&quot;ls&quot;);</code>) and get the stdout into a string.</p>
  <p>But what it does not do is get the command return code (pass/fail integer) or the stderr. Ideally I would like a way to get all three (return code, stdout, stderr).</p>
  <p>I would settle for stdout and stderr. I am thinking that I need to add another pipe, but I can't really see how the first pipe is setup to get stdout so I can't think how I would change it to get both.</p>
  <p>Any one got any ideas how to do that, or alternative approaches that may work?</p>
  <p><strong>update</strong></p>
  <p>See my complete example <a href="https://onlinegdb.com/SJ5qIk2vm" rel="noreferrer">here</a> with the output:</p>
  <pre><code>Start
  1 res: /home
  
  2 res: stdout
  
  stderr
  3 res: 
  End
  </code></pre>
  <p>You can see that <code>3 res:</code> does not print stderr in the same way that <code>2 res: stdout</code> does, but stderr is just dumped onto the screen on a separate line by the process (and not my program).</p>
  <p><strong>External Libs</strong></p>
  <p>I really don't want to use external libraries like Qt and boost - mostly because I want the portability of it and also many projects that I work on don't use boost. However I will mark up solutions that contain these options as they are valid for other users :)</p>
  <p><strong>Complete Solution Using Comments/Answer</strong></p>
  <p>Thanks all for your answers / comments, here is the modified solution (and runable):</p>
  <p><a href="https://onlinegdb.com/HJY9Ay2vm" rel="noreferrer">working-solution</a></p>