日期:2014-05-18  浏览次数:20743 次

怎样判断子进程已经结束 process.waitFor();的问题
ProcessBuild.command(commend);
  Process   process=   ProcessBuild.start();

  //
  public   void   run()   {
                try   {
                        System.out.println(   "waitFor() ");
                        process.waitFor();
                }
                catch(   InterruptedException   e)   {
                        throw   new   RuntimeException(   "InterruptedException   Exception   encountered ",   e);
                }
                if(   pro.exitValue()   !=   0)   {    
                        process.destroy();
                }
                System.out.println(   "exitValue ");
        }

不知道process.waitFor();这个方法会让当前线程一直等待下去不会停止,我想知道他结束之后能够打印出退出的消息.我就是想实现子进程结束后通知当前线程
希望各位能帮帮忙~~

------解决方案--------------------
process.waitFor();
是个组塞方法,如果子进程没有结束,它是不会返回的,

等子进程结束了,程序自然会继续执行下去,

你要问什么?
------解决方案--------------------
楼主,我也有你同样的问题呀,痛苦中的。
try {
ProcessBuilder builder = new ProcessBuilder();
builder.command(commend);
Process subprocess = builder.start();
subprocess.waitFor();
System.out.println(subprocess.exitValue());
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}

现在我的这段代码执行的情况是,子进程(subprocess)一直在等待主进程结束后,它执行,怎么刚好相反呢
------解决方案--------------------
这个问题前不久我刚遇到过,死锁了,看下帮助文档就知道了。
javadoc
The methods that create processes may not work well for special processes on certain native platforms, such as native windowing processes, daemon processes, Win16/DOS processes on Microsoft Windows, or shell scripts. The created subprocess does not have its own terminal or console. 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.waitFor();之前加上一下代码
BufferedReader br = new BufferedReader(process.getInputStream());
while(br.readLine()!=null);

通常这样可以解决,但是线程执行是由cpu控制的,如果process还没被执行,那么while(br.readLine()!=null);就会结束,此时如果process刚好被执行了,但由于while(br.readLine()!=null);已经结束了,process的输入流输出流还是没有被清空,到process.waitFor();时还是会造成堵塞的。

所以,一般我的做法是把上面的代码写到一个监视线程中,比如
class WatchThread extends Thread {
Process p;
boolean over;
public WatchThread(Process p) {