title: how to properly capture all stdout/stderr
body: <p>I want to capture and save to a file all the <a href="https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29" rel="nofollow">stdout</a> and <a href="https://en.wikipedia.org/wiki/Standard_streams#Standard_error_.28stderr.29" rel="nofollow">stderr</a></p>
  
  <p>For testing purposes I am printing only what I capture using this:</p>
  
  <p>package main</p>
  
  <pre><code>import (
      "bufio"
      "bytes"
      "fmt"
      "io"
      "os/exec"
  )
  
  func main() {
      cmd := exec.Command("/tmp/stdout")
      stdout := new(bytes.Buffer)
      stderr := new(bytes.Buffer)
  
      cmd.Stdout = stdout
      cmd.Stderr = stderr
  
      if err := cmd.Start(); err != nil {
          panic(err)
      }
  
      if err := cmd.Wait(); err != nil {
          panic(err)
      }
  
      in := bufio.NewScanner(io.MultiReader(stdout, stderr))
      for in.Scan() {
          fmt.Println(in.Text())
      }
  
  }
  </code></pre>
  
  <p>The <strong>/tmp/stdout</strong> command can be build using this code:</p>
  
  <pre class="lang-go prettyprint-override"><code>package main
  
  import (
      "fmt"
      "os"
      "time"
  )
  
  func main() {
  
      for i := 1; i &lt; 1000; i++ {
          if i%3 == 0 {
              fmt.Fprintf(os.Stderr, "STDERR i: %d\n", i)
          } else {
              fmt.Printf("STDOUT i: %d\n", i)
          }
          time.Sleep(1 * time.Second)
      }
  
  }
  </code></pre>
  
  <p>For some reason I am not been available to capture anything from the  output, If I run the <code>/tmp/stdout</code> command I get this:</p>
  
  <pre><code>$ /tmp/stdout 
  STDOUT i: 1
  STDOUT i: 2
  STDERR i: 3
  STDOUT i: 4
  STDOUT i: 5
  STDERR i: 6
  STDOUT i: 7
  </code></pre>
  
  <p>I was expecting to be available to get the same output while calling it from go with the previous code, the strange thing is that if I change to command to be something like <code>id</code>, <code>whoami</code> <code>uname</code> I do get the result and can printed, therefore wondering what could be wrong.</p>
  
  <p>Any ideas ?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Found that I have to wait the program to finish, as suggested in the comments in order to get the output, but in case I would like to get the output in realtime how could I achieve this, what could be the best way of doing it, either <code>io.Copy</code> an <code>os.Pipe</code>, etc ?</p>