如何連續讀取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中文網其他相關文章!