title: Copy stdout to stdin between java prcesses
body: <p>I try to copy one stdout of a process to the stdin to two new processes. But somehow this does not work as expected and is suprisingly hard to debug. What am I missing here?</p>
  
  <pre><code>public class Foo {
      public static void main(String[] args) throws Exception {
          Process pA = new ProcessBuilder("java", "-version").start();
          Process pB = new ProcessBuilder("bash", "-c", "cat").start();
  
          InputStream stdErrA = pA.getErrorStream();
          OutputStream stdInB = pB.getOutputStream();
          ByteArrayOutputStream cmdInB2 = new ByteArrayOutputStream();
  
          OutputStream tee = new TeeOutputStream(stdInB, cmdInB2);
          IOUtils.copy(stdErrA, tee);
          pA.waitFor();
          stdInB.close(); // EDIT: results mostly in the expected behavior, but throws IOException broken pipe sometimes
          pB.waitFor();
  
          String resultOfBOut = IOUtils.toString(pB.getInputStream(), "UTF-8");
          String copyOfAOut = cmdInB2.toString("UTF-8");
      }
  }
  </code></pre>