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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值