2016-08-23 46 views
0

我有以下的方法,该方法执行命令的过程和返回的输出中:加入一个线程/进程在Java中一段时间​​后 - Java的

public String execute(String command) { 
     StringBuffer output = new StringBuffer(); 
     Process p; 
     try { 
      p = Runtime.getRuntime().exec(command); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); 
      String line = ""; 
      while ((line = reader.readLine()) != null) { 
       output.append(line + "\n"); 
      } 
     } catch (Exception e) { 
      logger.error(e.getMessage()); 
     } 
     return output.toString(); 
    } 

此代码是伟大的,只要命令返回,但是对于继续运行流程,如top,这可能永远不会返回。代码不需要保持连续运行。它只需要捕捉一个快照,或者它可能会在一段时间后超时,比如3秒。我怎么能做到这一点?

回答

0

Process有一个方法waitFor。它可以用来强制超时。例如:

if ((p = Runtime.getRuntime().exec(execPath)) != null) && !p.waitFor(TIMEOUT_CONSTANT, TimeUnit.SECONDS)) { 
    p.destroyForcibly(); 
}