Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ExecChannel: How to correctly get the exit code #717

Open
Nexxurs opened this issue Nov 30, 2024 · 1 comment
Open

ExecChannel: How to correctly get the exit code #717

Nexxurs opened this issue Nov 30, 2024 · 1 comment

Comments

@Nexxurs
Copy link

Nexxurs commented Nov 30, 2024

Hey!

I have a question regarding the exitcode for single-command SSH connections.

I am currently using the following piece of code (in Kotlin - abbreviated to focus on the main points)

import com.jcraft.jsch.ChannelExec
import com.jcraft.jsch.JSch
import java.io.BufferedReader
import java.io.InputStreamReader
import com.jcraft.jsch.Session


fun createSession(): Session {
    return JSch().getSession("127.0.0.1")
}

fun run(command: String) {
    val channel = createSession().openChannel("exec") as ChannelExec
    
    try {
        channel.setCommand(command)
        val reader = BufferedReader(InputStreamReader(channel.inputStream))
        channel.connect()

        var lastLine = ""
        while (reader.readLine()?.also { lastLine = it } != null) {
            doStuff(lastLine)
        }
    } finally {
        channel.disconnect()
        while (!channel.isClosed) {
            Thread.sleep(10)
        }
        if (channel.exitStatus != 0) {
            throw Exception("something went wrong")
        }
    }
}

Rarely this fails on commands that I'd expect to run successfully (as the stdout output is correct, in these cases the exitStatus is -1) - I expect some kind of race condition. After checking the code, it looks like isClosed is set before the ChannelClose package is sent, whose response sets the exitStatus.

Is there a way to correctly read the exitStatus after the Channel is closed? AFAIK -1 is a valid exitStatus, which is why I cannot wait until this value changes (and it opens other issues with busy waiting)

If not, please consider this a feature request.

@mwiede
Copy link
Owner

mwiede commented Dec 16, 2024

have you considered the err input stream? see https://stackoverflow.com/a/47554723/2290153 for the explanation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants