如何连续读取 JSch 命令输出
通过 JSch 运行命令时,必须连续读取输出,以防止由于以下原因导致死锁完整的输出缓冲区。以下是如何实现这一点:
<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>
通过不断读取输出,命令执行不会被阻塞,并且可以根据需要检索和处理输出。
以上是读取 JSch 命令输出时如何避免死锁?的详细内容。更多信息请关注PHP中文网其他相关文章!