Home > Java > javaTutorial > body text

How to Avoid Deadlocks When Reading JSch Command Output?

Patricia Arquette
Release: 2024-11-02 06:26:29
Original
880 people have browsed it

How to Avoid Deadlocks When Reading JSch Command Output?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!