java runtime exec hang up 运行挂起的问题

当我们在java 里去执行平台系统命令时,有时候会碰到运行无响应的问题。这里主要是系统平台提供的缓存大小在作怪。

比如你执行ipconfig和ipconfig /all,系统返回的字符多少不一样。返回的字符串大于缓存,那么就会出问题。导致线程死在那里。

code :

String rs = null;
   try {
    Runtime rt = Runtime.getRuntime();
    Process proc = null;

     InputStreamReader isr = null;
     BufferedReader br = null;
     String line =null;
     proc = rt.exec("cmd /c ipconfig /all ");
     isr = new InputStreamReader(proc.getInputStream());
     br = new BufferedReader(isr);
     while ((line = br.readLine()) != null){
      if (line.contains("Physical Address")){
       line = line.substring(line.indexOf(":")+1);
       line = line.trim();
       line = line.replace("-", "");
       rs = line;
      
       break;
      }
     }
     proc.waitFor();
     proc.destroy();
    }

由于运行时io buffer的问题,当输出的字串大于buffer时会hang up. 所以read 此时的buffer时要注意。上面的代码可以解决这个问题,但是具体原因有待于查明。

问题主要出在proc.waitFor(); 要在waitFor之前处理掉buffer里的东西。另外一种方法就是,起一个单独的线程去处理buffer里的东西。

new PrintOut extends Thread{

   BufferedReader br;

   public PrintThread(InputStream is) {
    br = new BufferedReader(new InputStreamReader(is));
   }

   public void run() {
    String line;
    try {
     while (null != (line = br.readLine())) {
      System.out.println(">" + line);
     }
    } catch (IOException e) {
     e.printStackTrace();
    }
   }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值