Note that there are some explanatory texts on larger screens.

plurals
  1. POEnd Thread that is stuck in a InputStream.read() loop
    primarykey
    data
    text
    <p>I start a cmd application that outputs to System.out through this SyncPipe Runnable:</p> <pre><code>public class SyncPipe implements Runnable { private final InputStream is; private final OutputStream os; public SyncPipe(InputStream is, OutputStream os) { this.is = is; this.os = os; } public void run() { try { final byte[] buffer = new byte[1024]; for ( int length = 0; ( length = is.read(buffer) ) != -1; ) os.write(buffer, 0, length); System.out.print("stopped"); } catch ( Exception ex ) { ex.printStackTrace(); } } } </code></pre> <p>I start RunIt with <code>cmd = "C:/bin/read.exe -f D:/test.jpg"</code></p> <pre><code>private class RunIt implements Runnable { public int p; public String cmd; public RunIt (int p, String cmd) { this.p = p; this.cmd = cmd; } public void run() { ProcessBuilder pb = new ProcessBuilder("cmd"); try { process = pb.start(); (new Thread(new SyncPipe(process.getErrorStream(), System.err))).start(); (new Thread(new SyncPipe(process.getInputStream(), System.out))).start(); OutputStream out = process.getOutputStream(); out.write((cmd + "\r\n").getBytes()); out.flush(); out.close(); try { process.waitFor(); } catch ( InterruptedException e ) { e.printStackTrace(); } println("Stopped using %d.", p); } catch ( IOException ex ) { ex.printStackTrace(); } } } </code></pre> <p>My question now: How can I make <code>(new Thread(new SyncPipe(process.getErrorStream(), System.err)))</code> die? Giving SyncPipe a boolean variable <code>stop</code>, setting it <code>true</code> during runtime, and checking for it via <code>for ( int length = 0; ( length = is.read(buffer) ) != -1 &amp;&amp; !stop; )</code> did not do the trick.</p> <p>Thanks a lot in advance.</p> <hr> <p>I ended up doing the work-around that @Gray suggested. It works now:</p> <pre><code>public void run() { try { final byte[] buffer = new byte[1024]; do if ( is.available() &gt; 0 ) { int length = is.read(buffer); if ( length != -1 ) os.write(buffer, 0, length); else stop = true; } while ( !stop ); } catch ( Exception ex ) { ex.printStackTrace(); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload