`
enjoy2010
  • 浏览: 22735 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Runtime.getRuntime().exec常见问题

阅读更多

今天搞了一天,JAVA调用一个PERL程序,得不得就退不出,千试万试,LOG精细到逐行,知道在哪停住了,但打死不知道为什么。
后来吃个饭都放弃了,居然又找到答案,要没看到它,那真以为里面有鬼了。

大概原因是,调用Runtime.getRuntime().exec后,如果不及时捕捉进程的输出,会导致JAVA挂住,看似被调用进程没退出。所以,解决办法是,启动进程后,再启动两个JAVA线程及时的把被调用进程的输出截获。

一下子,整个世界清爽多了。。。多谢这么仁兄,下面转一下:



转自:http://pudding.sharera.com/blog/BlogTopic/31232.htm

碰到一个项目需要从Java中运行Perl程序,这个Perl程序调用客户的Web service,每次发送一个请求,接受一个响应。Java程序中包含多个请求,需要多次调用Perl程序,并且接受和解析响应(这个烂设计可不是我干 的,我实在不明白强大的Java Web Service为什么要弄成这样,不过客户是老大)。使用Java Runtime的exec()方法,发现运行一段时间后,进程就被挂起了(之前的响应完全正确)。于是分析原因,发现我在运行exec()方法后,立刻执 行了Process的waitFor()方法,这里出了问题。在网上找到一篇文章讲述这个问题:
地址:http://brian.pontarelli.com/2005/11/11/java-runtime-exec-can-hang/

Java Runtime exec can hang

November 11, 2005 on 4:40 pm | In Java |

The next version of Savant is going to focus heavily on the stand-alone runtime and support for dialects and plugins. Supporting all that is largely handled by using a simple executor framework I wrote around Java 1.4 and lower’s Runtime.exec method. A few things to keep in mind when using this:

  1. Always read from the streams prior to calling waitFor. Otherwise you could end up waiting forever on Windows and other OS platforms whose I/O buffers can’t store enough from standard out and standard error to ensure the program has finished. These platforms will pause the execution of whatever is running until something reads the buffered content from standard out and standard error. I would imagine all platforms suffer from this, but some platforms have larger buffers than others. Needless to say, always read from the streams first.
  2. Always read from standard error first. I ran across a bug where some OS platforms will always open standard out, but never close it. What this means is that if you read from standard out first and the process only writes to standard error, you’ll hang forever waiting to read. If you read from standard error first, you’ll always be okay on these platforms because the OS seems to shutdown standard error. I think however, that the best way to handle all cases is to check both standard error and standard out for readiness and only read from them if they have something to offer. The downside I could see here is that error isn’t ready, but eventually will be.

可以看出:

  • 永远要在调用waitFor()方法之前读取数据流
  • 永远要先从标准错误流中读取,然后再读取标准输出流

于是将waitFor()方法放在读取数据流后调用,目前没有发现什么问题。

正好解决了我心中的疑问,非常感谢!

我们的程序一开始就是exec完了接着waitFor(),但bat文件执行不完整:

Process proc = Runtime.getRuntime().exec(cmd);
                proc.waitFor();

后面的build中在waitFor()之前读取了数据流,bat文件就可以完整执行了:

Process proc = Runtime.getRuntime().exec(cmd);
     StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "Error");           
                 StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "Output");
                 errorGobbler.start();
                 outputGobbler.start();

     proc.waitFor();

class StreamGobbler extends Thread {
 InputStream is;

 String type;

 StreamGobbler(InputStream is, String type) {
  this.is = is;
  this.type = type;
 }

 public void run() {
  try {
   InputStreamReader isr = new InputStreamReader(is);
   BufferedReader br = new BufferedReader(isr);
   String line = null;
   while ((line = br.readLine()) != null) {
    if (type.equals("Error"))
     LogManager.logError(line);
    else
     LogManager.logDebug(line);
   }
  } catch (IOException ioe) {
   ioe.printStackTrace();
  }
 }
}

TestPrint.bat:

echo P1=%1  >D:"2.1.2env"2.1.2home"CompuSet"output"TestPrint.log
echo P2=%2 >>D:"2.1.2env"2.1.2home"CompuSet"output"TestPrint.log
echo P3=%3 >>D:"2.1.2env"2.1.2home"CompuSet"output"TestPrint.log
echo P4=%4 >>D:"2.1.2env"2.1.2home"CompuSet"output"TestPrint.log
echo P5=%5 >>D:"2.1.2env"2.1.2home"CompuSet"output"TestPrint.log
echo P6=%6 >>D:"2.1.2env"2.1.2home"CompuSet"output"TestPrint.log

Bad_TestPrint.log:

P1=C:"xPression"CompuSet"output"MartyTestOut1.afp 
P2=Literal1
P3="Rick Skinner"
P4=Parameter3

Good_TestPrint.log

P1=C:"xPression"CompuSet"output"MartyTestOut1.afp 
P2=Literal1
P3="Rick Skinner"
P4=Parameter3
P5=Parameter4
P6=Parameter5

分享到:
评论

相关推荐

    解决runtime.exec()执行进程block死锁以及为waitFor设置超时

    完美解决runtime.exec()执行进程block死锁以及为waitFor设置超时 不需要耗cpu的循环判断exitValue==0 开两个进程搞定

    Android中软件的静默安装

    1,申请root权限Runtime.getRuntime().exec("su"); 2,通过数据输出流DataOutputStream写入pm install命令; 3,最后获取Process进程的返回值int i = process.waitFor();,如果i=0,则表明已获取root权限。

    【IDEA】windows环境下IDEA java代码Runtime.getRuntime.exec中shell的执行环境的解决方案

    windows环境下IDEA java代码Runtime.getRuntime.exec中shell的执行环境的解决方案前言解决办法后记 前言 在使用IDEA本地开发监控守护线程的后台,我遇上了执行环境不兼容的问题,爆出各种“xxx不是内部或外部命令,...

    Runtime 执行bat

    Runtime 执行bat

    android截屏

    这里不是通过view来截图,也不是通过底层的framebuffer实现截图,而是采用另外一种方法实现截图,通过Runtime.getRuntime().exec()来实现,并保存在sdcard上,代码很简单。

    AIUI使用.rar

    Runtime runtime = Runtime.getRuntime(); try { runtime.exec("cmd /c start " + url); } catch (IOException e) { e.printStackTrace(); } } /** * 鍦ㄥ欢杩熸寚瀹氱殑绉掓暟鍚庡叧鏈? * ...

    Delphi实现android系统的步进电机控制.rar

     //Process p = Runtime.getRuntime().exec("su");  //然后,在向这个进程的写入要执行的命令,即可达到以root权限执行命令:  //dos.flush();  //或者用下面的方式:  //Runtime.getRuntime().exec&#...

    Java调用Linux命令

    (注意:Runtime.getRuntime().exec(command)返回的是一个Process类的实例), 该实例可用于控制进程或取得进程的相关信息. 由于调用Runtime.exec方法所创建的子进程没有自己的终端或控制台,因此该子进程的标准IO...

    Java编程使用Runtime和Process类运行外部程序的方法

    主要介绍了Java编程使用Runtime和Process类运行外部程序的方法,结合实例形式分析了java使用Runtime.getRuntime().exec()方法运行外部程序的常见情况与操作技巧,需要的朋友可以参考下

    runtimepermission

    动态权限工具类

    java实现动态波形曲线显示.rar

     java的Runtime.getRuntime().exec(commandStr)可以调用执行cmd指令。  cmd /c dir 是执行完dir命令后关闭命令窗口。  cmd /k dir 是执行完dir命令后不关闭命令窗口。  cmd /c start dir 会打开一个新...

    使用JAVA获取客户端MAC地址.doc

    利用Runtime call操作系统的命令,具体的命令取决于不同的操作系统,注意不要调用Runtime.getRuntime().exec(String)接口,要用Runtime.getRuntime().exec(String[])这个接口,不然复杂命令的执行会有问题。...

    echarts-convert.zip

    java用Runtime.getRuntime().exec(cmd)调用js即可,

    Java使用默认浏览器打开指定URL的方法(二种方法)

    直接看代码:方法一: 代码如下:Runtime.getRuntime().exec(“rundll32 url.dll,FileProtocolHandler //www.jb51.net”); 方法二: 代码如下://判断当前系统是否支持Java AWT Desktop扩展 if(java.awt....

    安卓程序发送linux指令.zip

    Runtime.getRuntime().exec("sh")以及linux echo写入指令

    java 查看任务管理里面的所有线程

    java 查看任务管理里面的所有线程 Proces java.lang.Runtime.getRuntime().exec("ipconfig");

    java修改文件属性

    所以我们必须到Dos环境下去设置,在java中用Runtime.getRuntime().exec("attrib " + """ + file.getAbsolutePath()+ """+ " +R")该方法可以实现。因为路径file.getAbsolutePath()中可能会还有空格,所以必须...

    python-runtime:用于可信自动化 Docker 构建的 Python 运行时 Dockerfile

    从公共下载: docker pull dockerfile/python-runtime (或者,您可以从 Dockerfile 构建映像: docker docker build -t="dockerfile/python-runtime" github.com/dockerfile/python-runtime ) 用法 此图像假定您...

    蜂鸣器exe,可用java调用

    蜂鸣器exe,可用java调用 Runtime.getRuntime().exec("d:\\beep.exe");

Global site tag (gtag.js) - Google Analytics