How to Continuously Read JSch Command Output
When running a command via JSch, it's essential to continuously read the output to prevent deadlocks resulting from a full output buffer. Here's how to achieve this:
<code class="java">ChannelExec channel = (ChannelExec)session.openChannel("exec"); channel.setCommand(...); ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream(); ByteArrayOutputStream errorBuffer = new ByteArrayOutputStream(); InputStream in = channel.getInputStream(); InputStream err = channel.getExtInputStream(); channel.connect(); while (!channel.isClosed()) { // Read stdout continuously while (in.available() > 0) { outputBuffer.write(in.read(tmp, 0, 1024)); } // Read stderr continuously while (err.available() > 0) { errorBuffer.write(err.read(tmp, 0, 1024)); } try { Thread.sleep(1000); } catch (Exception e) {} } System.out.println("output: " + outputBuffer.toString("UTF-8")); System.out.println("error: " + errorBuffer.toString("UTF-8")); channel.disconnect();</code>
By continuously reading the output, the command execution is not blocked and the output can be retrieved and processed as needed.
The above is the detailed content of How to Avoid Deadlocks When Reading JSch Command Output?. For more information, please follow other related articles on the PHP Chinese website!