随笔-50  评论-55  文章-8  trackbacks-0

现象:
        Runtime.exec() 方法创建标准的输出的管道。 当子进程,往完全缓冲区此管道写入大量数据时,它阻止在管道上直到管道缓冲区中的数据读取父进程。 如果父进程将永远不会读取标准输出, Process.waitFor() 不返回。
1、程序代码
      StringBuffer command = new StringBuffer();
      command .append("你需要的命令行");
      Runtime rt = Runtime.getRuntime();
      Process process=rt.exec(command.toString());
      int pflag = -1;
      //重要,解决死锁的方案
      new PrintStream(process.getInputStream()).start();
      pflag=process.waitFor();
      if(pflag!=-1){
       System.out.println("执行成功!");
     }
     类PrintStream,网上找的,主要是打印信息
    class PrintStream extends Thread{
     java.io.InputStream __is = null;
      public PrintStream(java.io.InputStream is)  {
        __is = is;
      }

     public void run() {
       try  {
       while(this != null) {
       int _ch = __is.read();
     if(_ch != -1)
      System.out.print((char)_ch);
     else break;
    }
   }
   catch (Exception e)
   {
    e.printStackTrace();
   }
  }
 }
2、解决方案
      若要避免阻止,请确保父进程始终读取标准输出从子进程。

posted on 2009-01-04 16:38 蒋家狂潮 阅读(649) 评论(0)  编辑  收藏 所属分类: Basic

只有注册用户登录后才能发表评论。


网站导航: