title: How to properly terminate a Process prematurely?
body: <p>I'm having an issue with properly closing a <code>Process</code> before it completes. I'm using a <code>ProcessBuilder</code> in order to create a new <code>Process</code> with one of the following two scenarios:</p>
  <ol>
  <li>Complete the process and read it's output via a <code>BufferedReader</code></li>
  <li>Don't wait for output from the <code>Process</code>, so just give it some time to run and then terminate it (even if it's not completed, I want it to terminate).</li>
  </ol>
  <p>The code I wrote so far is:</p>
  <pre class="lang-java prettyprint-override"><code>public static String runCommand(List&lt;String&gt; commandList, boolean returnOutput) throws InterruptedException {
      ProcessBuilder pb = new ProcessBuilder(commandList);
      pb.redirectErrorStream(true);
          
      StringBuilder output = new StringBuilder();
      try {
          Process p = pb.start();
              
          if(!returnOutput) {
              p.waitFor(1, TimeUnit.MINUTES);
              p.destroy();
              if(!p.waitFor(20, TimeUnit.SECONDS))
                  p.destroyForcibly();
              
              p.getInputStream().close();
              p.getOutputStream().close();
              System.out.println(p.isAlive());
              return null;
          }
                  
          BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
                  
          String line;
          while((line = reader.readLine()) != null) {
              output.append(line);
              output.append(&quot;\n&quot;);
          }
              
          reader.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
      
      return output.toString();
  }
  </code></pre>
  <p>The problem is related to scenario 1, because even though the Process is terminated inside the <code>if(!returnOutput)</code> since the <code>System.out.println</code> returns <code>false</code> for the <code>p.isAlive()</code> and I can get the expected results, I can see in the task manager (Windows) that it is still running...</p>
  <p>I've checked previous answers but nothing worked so far. Any help would be greatly appreciated!</p>