问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/22734134/wait-for-jsch-command-to-execute-instead-of-hard-coding-a-fixed-time-to-wait-for