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

前端 未结 17 1858
长发绾君心
长发绾君心 2020-11-27 12:08

I have a method I am using to execute a command on the local host. I\'d like to add a timeout parameter to the method so that if the command being called doesn\'t finish in

17条回答
  •  甜味超标
    2020-11-27 12:22

    public static int executeCommandLine(final String commandLine,
                                         final boolean printOutput,
                                         final boolean printError,
                                         final long timeout)
          throws IOException, InterruptedException, TimeoutException {
      Runtime runtime = Runtime.getRuntime();
      Process process = runtime.exec(commandLine);
      /* Set up process I/O. */
      ... 
      Worker worker = new Worker(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.destroyForcibly();
      }
    }
    
    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;
        }
      }  
    }
    

提交回复
热议问题