Java Process waitFor() 挂死问题

1.JDK文档中明确提到

All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (getOutputStream(),getInputStream(),getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. 

Because some native platforms only provide limited buffer size for standard input and output streams,

 failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.


Process.exitValue() 采用非阻塞的方式返回,如果没有立即拿到返回值,则抛出异常

Process.waitFor() 当前线程等待,如有必要,一直要等到由该 Process 对象表示的进程已经终止。但是如果我们在调用此方法时,如果不注意的话,很容易出现主线程阻塞,Process也挂起的情况。在调用waitFor() 的时候,Process需要向主线程汇报运行状况,所以要注意清空缓存区,即InputStream和ErrorStream.


2. 代码片段

normalReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
errorReader  = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while((line = normalReader.readLine()) != null){
    logger.info(line);
}
while((line = errorReader.readLine()) != null){
    logger.error(line);
}


3. 延伸阅读

http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html


4. JDK5中新增Processbuilder

http://www.java-tips.org/java-se-tips/java.util/from-runtime.exec-to-processbuilder.html

你可能感兴趣的:(Java)