codecrazy46
codecrazy46

Reputation: 297

Wait for JSch command to execute instead of hard coding a fixed time to wait for

Channel channel=session.openChannel("shell");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
while (channel.getExitStatus() == -1){
   try{Thread.sleep(1000);}catch(Exception e){System.out.println(e);}
}   
channel.disconnect();

In the code above we add line Thread.sleep(1000); to give the system enough time, to execute the command. However when I change the time gap from 1000 ms to 200 ms, the command doesn't execute.

Also in some slow servers, the command may not execute for the specified time gap of 1000 ms too. Is there any other dynamic way to wait for the command to execute completely before the next starts executing instead of hard coding the value, especially required while automating?

Upvotes: 2

Views: 6787

Answers (1)

gmavrikas
gmavrikas

Reputation: 31

You have to loop reading chunks of the response until channel.isClosed() returns true.

At that point you can call channel.getExitStatus() to get the process exit code and then close the channel.

If you don't want to burn CPU cycles while looping to read the response bytes, put a Thread.sleep(100) between each read.

Upvotes: 3

Related Questions