title: How do I sequentially execute wsl commands from java?
body: <p>I want to execute <code>wsl</code> commands from <code>java</code>. </p>
  
  <p>I'm trying to do this using <code>Process</code> and <code>ProcessBuilder</code>.</p>
  
  <p>As I understand, there are two ways to do this:</p>
  
  <ol>
  <li>Run <code>wsl</code> along with command as argument (for example: <code>wsl ls -l</code>) (do this per-command).</li>
  <li>Run <code>wsl</code>, and then execute the commands one by one.</li>
  </ol>
  
  <p>But there are some problems with <code>1</code> and <code>2</code>.</p>
  
  <p><strong>With point <code>1</code>:</strong></p>
  
  <ol>
  <li>When the command terminates, the process does not stop. So even if i run <code>wsl ls</code>, I can not determine the moment when I can call next command.</li>
  <li><code>wsl</code> does not save the state between such calls, so it's not very convenient</li>
  </ol>
  
  <p><strong>With point <code>2</code>:</strong></p>
  
  <p>Since <code>wsl</code> does not show <code>bash prompt</code>, I can not track when the command stopped displaying information. For example: </p>
  
  <pre><code>ProcessBuilder pb = new ProcessBuilder("wsl");
  pb.redirectErrorStream(true);
  Process p = pb.start();
  Thread.sleep(1000);
  OutputStreamWriter osw = new OutputStreamWriter(p.getOutputStream());
  osw.write("ls\n");
  osw.flush();
  </code></pre>
  
  <p>And all I can read is: </p>
  
  <pre><code>build.gradle
  gradle
  gradlew
  gradlew.bat
  out
  settings.gradle
  src 
  </code></pre>
  
  <p>No <code>selya@selya-pc:/mnt/c/Users/selya$</code> read. So I can't use it as a separator between commands. I think that <code>wsl</code> somehow tracks, in what environment it was launched, for example, through <code>isatty()</code>, and therefore the output is different.</p>
  
  <p><strong>With both:</strong></p>
  
  <p>Аs far as I know, for programs that are running outside the terminal, <code>stdout</code> is not buffered. So there are some problems with, for example, <code>sudo</code>, because it asks fro a password without <code>newline</code>/<code>flush</code> (<code>[sudo] password for selya:</code>), therefore I can't read this line... </p>
  
  <p>I found a solution - pass command as argument to <code>unbuffer</code> util, for example:</p>
  
  <pre><code>wsl unbuffer -p sudo apt-get update 
  </code></pre>
  
  <p>(<code>-p</code> stands for <code>pipeline</code>).</p>
  
  <p>But other problems still remain. Is there any way to do this? Or maybe there is lib for it? Even <code>c</code> or <code>c++</code> lib will suit my needs...</p>
  
  <p>P.S. I tried to find a solution for several days. Russian-speaking SO didn't help me, that's why I'm here. Sorry for my English...</p>