zoukankan      html  css  js  c++  java
  • 调用Runtime.exec()的一些陷阱 【转】

    转自:  http://berdy.iteye.com/blog/810223

    Runtime 封装着java程序的运行时环境。通过Runtime实例,java应用能够与其运行的环境连接。Runtime在jvm中保持一个单例,所以不能通过Runtime类的构造函数。只能通过Runtime.getRuntime()来获的当前Runtime的一个实例。获得Runtime实例后,就可以通过Runtime的exec()方法在当前jvm进程外启动其他进程了。很常见的一个应用就是,启动浏览器进程来显示一个程序的帮助页面。 

    在Runtime类中存在四个exec()重载方法. 

    Java代码  收藏代码
    1. public Process exec(String command);  
    2. public Process exec(String [] cmdArray);  
    3. public Process exec(String command, String [] envp);  
    4. public Process exec(String [] cmdArray, String [] envp);  


    主要参数是要启动进程的名称,以及启动该进程时需要的参数。然后是一些环境相关的属性。envp是已name=value, 
    形式传入的。具体查看下源码便一目了然了。 

        通常,启动另外一个进程后,需要获取另外一个进程的执行结果,然后根据结果执行后续的流程。要获取外部进程的运行结果,可以调用Process的exitValue() 方法。下面代码中启动一个java编译器进程。 

    Java代码  收藏代码
    1. try {  
    2.     Runtime rt = Runtime.getRuntime();  
    3.     Process proc = rt.exec("javac");  
    4.     int exitVal = proc.exitValue();  
    5.     System.out.println("Process exitValue: " + exitVal);  
    6. catch (Throwable t) {  
    7.     t.printStackTrace();  
    8. }  


    不幸的是,你将看到下面的结果: 
    java.lang.IllegalThreadStateException: process has not exited 
    at java.lang.ProcessImpl.exitValue(Native Method) 
    at com.test.runtime.Test.BadExecJavac(Test.java:13) 
    at com.test.runtime.Test.main(Test.java:5) 

    原因是exitValue()方法并不会等待外部进程结束。如果外部进程还未结束,exitValue()将会抛出IllegalThreadStateException。解决办法就是调用Process的waitfor()方法。waitfor()方法会挂起当前线程,一直等到外部进程结束。当然使用exitValue()或者waitfor()完全取决你的需求。可以设个boolean标志,来确定使用哪个。运行下面的代码: 

    Java代码  收藏代码
    1. try {  
    2.     Runtime rt = Runtime.getRuntime();  
    3.     Process proc = rt.exec("javac");  
    4.     int exitVal = proc.waitFor();  
    5.     System.out.println("Process exitValue: " + exitVal);  
    6. catch (Throwable t) {  
    7.     t.printStackTrace();  
    8. }  


    发现程序被阻塞了,什么原因呢?JDK's Javadoc文档解释说: 
    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. 
    翻译: 
    一些平台只为标准输入输出提供有限的缓存。错误的写子进程的输入流或者错误的都子进程的输出流都有可能造成子进程的阻塞,甚至是死锁。 

    解决上面问题的办法就是程序中将子进程的输出流和错误流都输出到标准输出中。 

    Java代码  收藏代码
    1. try {  
    2.     Runtime rt = Runtime.getRuntime();  
    3.     Process proc = rt.exec("javac");  
    4.     InputStream stderr = proc.getErrorStream();  
    5.     InputStreamReader isr = new InputStreamReader(stderr);  
    6.     BufferedReader br = new BufferedReader(isr);  
    7.     String line = null;  
    8.     System.out.println("<ERROR>");  
    9.     while ((line = br.readLine()) != null)  
    10.         System.out.println(line);  
    11.     System.out.println("</ERROR>");  
    12.     int exitVal = proc.waitFor();  
    13.     System.out.println("Process exitValue: " + exitVal);  
    14. catch (Throwable t) {  
    15.     t.printStackTrace();  
    16. }  


    上面的代码中仅仅是输出了错误流,并没有输出子进程的输出流。在程序中最好是能将子进程的错误流和输出流都能输出并清空。 

    在windows系统中,很多人会利用Runtime.exec()来调用不可执行的命令。例如dir和copy; 

    Java代码  收藏代码
    1. try {  
    2.     Runtime rt = Runtime.getRuntime();  
    3.     Process proc = rt.exec("dir");  
    4.     InputStream stdin = proc.getInputStream();  
    5.     InputStreamReader isr = new InputStreamReader(stdin);  
    6.     BufferedReader br = new BufferedReader(isr);  
    7.     String line = null;  
    8.     System.out.println("<OUTPUT>");  
    9.     while ((line = br.readLine()) != null)  
    10.         System.out.println(line);  
    11.     System.out.println("</OUTPUT>");  
    12.     int exitVal = proc.waitFor();  
    13.     System.out.println("Process exitValue: " + exitVal);  
    14. catch (Throwable t) {  
    15.     t.printStackTrace();  
    16. }  


    运行上面的代码,将会得到一个错误代码为2的错误。在win32系统中,error=2表示文件未找到。也就是不存在dir.exe和copy.exe。这是因为dir命令式windows中命令行解析器的一部分,并不是单独的一个可执行的命令。要运行上面的命令,得先启动windows下的命令行解析器command.com或者cmd.exe,这个取决于windows的系统的版本。 

    Java代码  收藏代码
    1. import java.io.BufferedReader;  
    2. import java.io.IOException;  
    3. import java.io.InputStream;  
    4. import java.io.InputStreamReader;  
    5.   
    6. class StreamGobbler extends Thread {  
    7.     InputStream is;  
    8.     String type;  
    9.   
    10.     StreamGobbler(InputStream is, String type) {  
    11.         this.is = is;  
    12.         this.type = type;  
    13.     }  
    14.   
    15.     public void run() {  
    16.         try {  
    17.             InputStreamReader isr = new InputStreamReader(is);  
    18.             BufferedReader br = new BufferedReader(isr);  
    19.             String line = null;  
    20.             while ((line = br.readLine()) != null)  
    21.                 System.out.println(type + ">" + line);  
    22.         } catch (IOException ioe) {  
    23.             ioe.printStackTrace();  
    24.         }  
    25.     }  
    26. }  
    27.   
    28. public class GoodWindowsExec {  
    29.     public static void main(String args[]) {  
    30.         if (args.length < 1) {  
    31.             System.out.println("USAGE: java GoodWindowsExec <cmd>");  
    32.             System.exit(1);  
    33.         }  
    34.   
    35.         try {  
    36.             String osName = System.getProperty("os.name");  
    37.             String[] cmd = new String[3];  
    38.             if (osName.equals("Windows NT")) {  
    39.                 cmd[0] = "cmd.exe";  
    40.                 cmd[1] = "/C";  
    41.                 cmd[2] = args[0];  
    42.             } else if (osName.equals("Windows 95")) {  
    43.                 cmd[0] = "command.com";  
    44.                 cmd[1] = "/C";  
    45.                 cmd[2] = args[0];  
    46.             }  
    47.   
    48.             Runtime rt = Runtime.getRuntime();  
    49.             System.out.println("Execing " + cmd[0] + " " + cmd[1] + " " + cmd[2]);  
    50.             Process proc = rt.exec(cmd);  
    51.   
    52.             StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");  
    53.   
    54.             StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");  
    55.   
    56.             errorGobbler.start();  
    57.             outputGobbler.start();  
    58.   
    59.             int exitVal = proc.waitFor();  
    60.             System.out.println("ExitValue: " + exitVal);  
    61.         } catch (Throwable t) {  
    62.             t.printStackTrace();  
    63.         }  
    64.     }  
    65. }  


    另外,Runtime.exec()并不是命令解析器,这是启动某个进程。并不能执行一些命令行的命令。下面是一个常见的错误: 

    Java代码  收藏代码
    1. try {  
    2.     Runtime rt = Runtime.getRuntime();  
    3.     Process proc = rt.exec("java jecho 'Hello World' > test.txt");  
    4.   
    5.     StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");  
    6.   
    7.     StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");  
    8.   
    9.     errorGobbler.start();  
    10.     outputGobbler.start();  
    11.   
    12.     int exitVal = proc.waitFor();  
    13.     System.out.println("ExitValue: " + exitVal);  
    14. catch (Throwable t) {  
    15.     t.printStackTrace();  
    16. }  


    上面的代码希望像DOS系统中一样将命令的执行结果输出到文件中去。但是Runtime.exec()并不是命令行解析器。要想重定向输出流,必须在程序中编码实现。 

    Java代码  收藏代码
      1. import java.util.*;  
      2. import java.io.*;  
      3.   
      4. class StreamGobbler extends Thread {  
      5.     InputStream is;  
      6.     String type;  
      7.     OutputStream os;  
      8.   
      9.     StreamGobbler(InputStream is, String type) {  
      10.         this(is, type, null);  
      11.     }  
      12.   
      13.     StreamGobbler(InputStream is, String type, OutputStream redirect) {  
      14.         this.is = is;  
      15.         this.type = type;  
      16.         this.os = redirect;  
      17.     }  
      18.   
      19.     public void run() {  
      20.         try {  
      21.             PrintWriter pw = null;  
      22.             if (os != null)  
      23.                 pw = new PrintWriter(os);  
      24.             InputStreamReader isr = new InputStreamReader(is);  
      25.             BufferedReader br = new BufferedReader(isr);  
      26.             String line = null;  
      27.             while ((line = br.readLine()) != null) {  
      28.                 if (pw != null)  
      29.                     pw.println(line);  
      30.                 System.out.println(type + ">" + line);  
      31.             }  
      32.             if (pw != null)  
      33.                 pw.flush();  
      34.         } catch (IOException ioe) {  
      35.             ioe.printStackTrace();  
      36.         }  
      37.     }  
      38. }  
      39.   
      40. public class GoodWinRedirect {  
      41.     public static void main(String args[]) {  
      42.         if (args.length < 1) {  
      43.             System.out.println("USAGE java GoodWinRedirect <outputfile>");  
      44.             System.exit(1);  
      45.         }  
      46.   
      47.         try {  
      48.             FileOutputStream fos = new FileOutputStream(args[0]);  
      49.             Runtime rt = Runtime.getRuntime();  
      50.             Process proc = rt.exec("java jecho 'Hello World'");  
      51.   
      52.             StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");  
      53.             StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT", fos);  
      54.   
      55.             errorGobbler.start();  
      56.             outputGobbler.start();  
      57.   
      58.             int exitVal = proc.waitFor();  
      59.             System.out.println("ExitValue: " + exitVal);  
      60.             fos.flush();  
      61.             fos.close();  
      62.         } catch (Throwable t) {  
      63.             t.printStackTrace();  
      64.         }  
      65.     }  
      66. }  
  • 相关阅读:
    数据库中随机返回n条数据的方法
    sql中NULL之恨
    数据库性能的查询优化特刊待续
    sql中exists替换in的区别
    代码的效率问题看一下代码
    检测数据库性能的方法
    Linux随堂1
    设置网页的图标
    C# 线程、timer例句
    转:1.2 Oracle表空间的操作
  • 原文地址:https://www.cnblogs.com/nkxyf/p/2815978.html
Copyright © 2011-2022 走看看