Java runtime getruntime exec timeout returns exit always NULL and always TimeoutException?

Referring to

How to add a timeout value when using Runtime.exec ()?

But I always get employee.exit NULL, so it always throws a timeout exception. Below is my code

public class MyClass { private static class Worker extends Thread { private final Process process; private Integer exit; private Worker(Process process) { this.process = process; } public void run() { try { exit = process.waitFor(); } catch (InterruptedException ignore) { return; } } } public String run(String command, long replyTimeout) throws Exception { StringBuffer output = new StringBuffer(); Process p; p = Runtime.getRuntime().exec(command); BufferedReader errReader = new BufferedReader(new InputStreamReader( p.getErrorStream())); BufferedReader inputReader = new BufferedReader(new InputStreamReader( p.getInputStream())); Worker worker = new Worker(p); worker.start(); try { worker.join(replyTimeout); if (worker.exit != null) { if (worker.exit > 0) { String line = ""; while ((line = errReader.readLine()) != null) { output.append(line + "\n"); } System.out.println(output.toString()); System.out.println(worker.exit); throw new Exception(output.toString()); } else { String line = ""; while ((line = inputReader.readLine()) != null) { output.append(line + "\n"); } System.out.println(output.toString()); System.out.println(worker.exit); return output.toString(); } } else { throw new TimeoutException(); } } catch (InterruptedException ex) { worker.interrupt(); Thread.currentThread().interrupt(); throw ex; } finally { p.destroy(); } } } 
0
java
May 20 '14 at 9:45
source share
1 answer

You do it all wrong. You must consume all the output of the process, both on stdout and stderr, before it makes sense to call waitFor (). Otherwise, the process may block an attempt to write its own output.

NullPointerExceptions, on the other hand, are simply due to trivial coding errors that you are expected to be able to smooth out on your own. At least I expect it.

+3
May 20 '14 at 10:09
source share



All Articles