I have implemented a way to timeout my process
running iperf server side based on this question's top answear and it works as intended but I am not sure how to destroy a process
object that I pass inside Task's
class constructor.
This is my modified code:
public class Main {
public static void main(String[] args) throws IOException {
Process p=null;
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new Task(p));
try {
System.out.println("Started..");
System.out.println(future.get(5, TimeUnit.SECONDS));
System.out.println("Finished!");
} catch (TimeoutException | InterruptedException | ExecutionException e) {
future.cancel(true);
//gives NullPointerException as expected after thread times out
p.destroyForcibly();
System.out.println("Terminated!");
}
executor.shutdownNow();
}
}
class Task implements Callable<String> {
Process p;
public Task(Process p) {
this.p = p;
}
@Override
public String call() throws Exception {
String s;
String toDisplay = "";
this.p = Runtime.getRuntime().exec("iperf3.exe -s -1");
BufferedReader br = new BufferedReader(new InputStreamReader(this.p.getInputStream()));
while ((s = br.readLine()) != null) {
toDisplay += s + "\n";
}
p.destroyForcibly();
return toDisplay;
}
}
I am guessing I should somehow set
main's
Process
but I have no idea how to aproach this problem