public int executeCommand(final String command, final long timeout) throws IOException, InterruptedException, TimeoutException {
Process process = Runtime.getRuntime().exec("ping -c 3 -w 100 "+command);
PingWorker worker = new PingWorker(process);
worker.start();
try {
worker.join(timeout);
if (worker.exit != null){
return worker.exit;
} else{
throw new TimeoutException();
}
} catch (InterruptedException ex) {
worker.interrupt();
Thread.currentThread().interrupt();
throw ex;
} finally {
process.destroy();
}
}
class PingWorker extends Thread{
private final Process process;
private Integer exit;
public PingWorker(Process process){
this.process = process;
}
@Override
public void run() {
try {
exit = process.waitFor();
} catch (InterruptedException e) {
return;
}
}
}
Process process = Runtime.getRuntime().exec("ping -c 3 -w 100 "+command);
PingWorker worker = new PingWorker(process);
worker.start();
try {
worker.join(timeout);
if (worker.exit != null){
return worker.exit;
} else{
throw new TimeoutException();
}
} catch (InterruptedException ex) {
worker.interrupt();
Thread.currentThread().interrupt();
throw ex;
} finally {
process.destroy();
}
}
class PingWorker extends Thread{
private final Process process;
private Integer exit;
public PingWorker(Process process){
this.process = process;
}
@Override
public void run() {
try {
exit = process.waitFor();
} catch (InterruptedException e) {
return;
}
}
}