Menu

#133 multiple sessions, channel inputstream read, hangs forever

v1.0 (example)
open
nobody
9
2021-02-17
2021-02-17
No
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(cmd);
channel.setInputStream(stdin);
channel.setErrStream(stderr);
channel.connect();
InputStream stdout = channel.getInputStream();
byte[] buffer = new byte[100000];
ByteArrayOutputStream out = new ByteArrayOutputStream();

do {
    if (stdout.available() > 0) {
        int n = stdout.read(buffer);
        if (n < 0) {
            break;
        }
        out.write(buffer, 0, n);
    } else {
        if (channel.isClosed() || !channel.isConnected() || channel.isEOF()) {
            // it could happen that there is still some data buffered
            int n = stdout.read(buffer);
            if (n > 0) {
                out.write(buffer, 0, n);
            }
            break;
        }
    }
} while (true);

The above code hangs at "stdout.read(buffer);" , if multiple sessions are created ( in my system, at around 25 or more sessions concurrently). I checked the thread dump and the code was stuck at the "stdout.read(buffer)" line. Some of the sessions complete the command and return, but some will hang forever..

Whereas the below code works even for more than 150 concurrent sessions

ByteArrayOutputStream stderr = new ByteArrayOutputStream();
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
ByteArrayInputStream stdin = new ByteArrayInputStream(in.getBytes("ASCII"));
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(cmd);
channel.setInputStream(stdin);
channel.setOutputStream(stdout);
channel.setErrStream(stderr);
channel.connect();

while (channel.isConnected()) {
    Thread.sleep(100);
}
int status = channel.getExitStatus();
String cmdOutput = new String(stdout.toByteArray());
String cmdErr = new String(stderr.toByteArray());

Tried this with jsch version 0.1.55.
Please fix this.

Discussion


Log in to post a comment.

MongoDB Logo MongoDB