/** * Start the application * * @throws IOException if there is a problem with connection * @throws InterruptedException if thread was interrupted */ private void start() throws IOException, InterruptedException { Connection c = new Connection(myHost.getHostName(), myHost.getPort()); try { configureKnownHosts(c); c.connect(new HostKeyVerifier()); authenticate(c); final Session s = c.openSession(); try { s.execCommand(myCommand); // Note that stdin is not being waited using semaphore. // Instead, the SSH process waits for remote process exit // if remote process exited, none is interested in stdin // anyway. forward("stdin", s.getStdin(), System.in, false); forward("stdout", System.out, s.getStdout(), true); forward("stderr", System.err, s.getStderr(), true); myForwardCompleted.acquire(2); // wait only for stderr and stdout s.waitForCondition(ChannelCondition.EXIT_STATUS, Long.MAX_VALUE); Integer exitStatus = s.getExitStatus(); if (exitStatus == null) { // broken exit status exitStatus = 1; } System.exit(exitStatus.intValue() == 0 ? myExitCode : exitStatus.intValue()); } finally { s.close(); } } finally { c.close(); } }
private int waitCompletion(Session session) throws InterruptedException { // I noticed that the exit status delivery often gets delayed. Wait up to 1 sec. for (int i = 0; i < 10; i++) { Integer r = session.getExitStatus(); if (r != null) return r; Thread.sleep(100); } return -1; }