`

When Runtime.exec() won't - Runtime.exec的陷阱

    博客分类:
  • Java
阅读更多

     原文比较长,在这里就不转载了,给出地址:http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=1

  1. 文中总结了几个要点:
    You cannot obtain an exit status from an external process until it has exited
    直到一个外部进程退出,你才能获取其退出状态值。
    正确代码
    int exitVal = proc.waitFor();
     缺陷代码
    int exitVal = proc.exitValue();
     
  2. You must immediately handle the input, output, and error streams from your spawned external process
    你必须马上处理从外部进程获得的大量输入、输出以及错误流(如果存在的话)。之所以要这样来做,是因为“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 Doc:某些本地平台只提供了有限的buffer给标准输入、输出流。一旦写入失败,子进程就有可能被阻塞甚至死锁。)
    正确代码
    import java.util.*;
    import java.io.*;
    public class MediocreExecJavac
    {
        public static void main(String args[])
        {
            try
            {            
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec("javac");
                InputStream stderr = proc.getErrorStream();
                InputStreamReader isr = new InputStreamReader(stderr);
                BufferedReader br = new BufferedReader(isr);
                String line = null;
                System.out.println("<ERROR>");
                while ( (line = br.readLine()) != null)
                    System.out.println(line);
                System.out.println("</ERROR>");
                int exitVal = proc.waitFor();
                System.out.println("Process exitValue: " + exitVal);
            } catch (Throwable t)
              {
                t.printStackTrace();
              }
        }
    }
      
    缺陷代码
    import java.util.*;
    import java.io.*;
    public class BadExecJavac2
    {
        public static void main(String args[])
        {
            try
            {            
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec("javac");
                int exitVal = proc.waitFor();
                System.out.println("Process exitValue: " + exitVal);
            } catch (Throwable t)
              {
                t.printStackTrace();
              }
        }
    }
    
      
  3. You must use Runtime.exec() to execute programs
     你必须使用Runtime.exec()来执行程序(这句我不太理解)
  4. You cannot use Runtime.exec() like a command line
    你不能用Runtime.exec()来执行像命令行那样的程序,如重定向输出:Process proc = rt.exec("java jecho 'Hello World' > test.txt"); 
    这段程序的意图是运行一个名为jecho的Java程序,并将其输出重定向到test.txt文件中。 但这种写法得不到正确结果,因为Runtime.exec()方法并不能很好的执行这种较为复杂的命令行,必须通过自己处理程序输出并写入到相应的文件

 最后给出完整的代码:

Class StreamGobbler 用于处理输出流:

import java.util.*;
import java.io.*;
class StreamGobbler extends Thread
{
    InputStream is;
    String type;
    OutputStream os;
    
    StreamGobbler(InputStream is, String type)
    {
        this(is, type, null);
    }
    StreamGobbler(InputStream is, String type, OutputStream redirect)
    {
        this.is = is;
        this.type = type;
        this.os = redirect;
    }
    
    public void run()
    {
        try
        {
            PrintWriter pw = null;
            if (os != null)
                pw = new PrintWriter(os);
                
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line=null;
            while ( (line = br.readLine()) != null)
            {
                if (pw != null)
                    pw.println(line);
                System.out.println(type + ">" + line);    
            }
            if (pw != null)
                pw.flush();
        } catch (IOException ioe)
            {
            ioe.printStackTrace();  
            }
    }
}

 TestExec则是测试用的main class

import java.util.*;
import java.io.*;
public class TestExec
{
    public static void main(String args[])
    {
        if (args.length < 1)
        {
            System.out.println("USAGE: java TestExec \"cmd\"");
            System.exit(1);
        }
        
        try
        {
            String cmd = args[0];
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(cmd);
            
            // any error message?
            StreamGobbler errorGobbler = new 
                StreamGobbler(proc.getErrorStream(), "ERR");            
            
            // any output?
            StreamGobbler outputGobbler = new 
                StreamGobbler(proc.getInputStream(), "OUT");
                
            // kick them off
            errorGobbler.start();
            outputGobbler.start();
                                    
            // any error???
            int exitVal = proc.waitFor();
            System.out.println("ExitValue: " + exitVal);
        } catch (Throwable t)
          {
            t.printStackTrace();
          }
    }
}

 

测试例子: java TestExec "iexplore www.sina.com.cn" (因为iexplore.exe已经在windows的环境变量Path中,所以这些调用没有问题,否则就要写绝对路径) 

2
0
分享到:
评论
1 楼 slowman 2009-05-27  


学习了,谢谢!

相关推荐

    when Runtime.exec&#40;&#41; won't 中文翻译版

    将runtime.exec()的四个陷阱用中文描述

    Jam.ShellBrowser.8.1.2.2013-03-06

    Bugfix - TJamBrowseForFolder: Fixed a bug where the path property couldn't always be set when using Delphi 18}. A major code cleanup was performed and numerous minor fixes and improvements have been ...

    juel-Tomcat与EL冲突问题

    启动Tomcat时报错:Caused by: java.lang.LinkageError: loader constraints violated when linking javax/el/ExpressionFactory class 说明:原因是juel.jar, juel-engine.jar, juel-impl.jar包和Tomcat6.0中的el-...

    Berg Soft Next Suite 5 1.2013Delphi 7 - XE3

    =========== Jan 15 2013 ... When set to true, item will be expanded on select. added: OnPropertyLoad event. Occur after LoadProperties method is called. added: OnPropertyLoaded event.

    [Diskeeper.磁盘整理软件服务器版].Diskeeper.2010.Enterprise.Server.v14.0.909.Incl.Patch.And.Keymaker-AGAiN.rar

    *Start diskeeper service, press cancel when the expiring message pops up, run Diskeeper application, in the menus you will find an option to enter license key, enter the previously generated key. *...

    官网下载:Windows-KB841290-x86-ENU.zip

    When you suspect that your system has been compromised, you can run a verification to determine which files have been modified. You can also schedule verifications regularily. 2.Features: -----------...

    wget-1.11.4-1

    -t, --tries=NUMBER set number of retries to NUMBER (0 unlimits). --retry-connrefused retry even if connection is refused. -O, --output-document=FILE write documents to FILE. -nc, --no-clobber skip...

    Keil.STM32F1xx-DFP.2.4.1.pack MDK5-F1系列最新pack包

    Version 2.4.1: May 12, 2023 Recommended Download 2.4.1 Board Support: - Corrected GLCD_...-- Corrected SetMode function to clear Silent and Loopback mode when NORMAL mode is activated. - EMAC, DMA:

    windows版wget命令

    -H, --span-hosts go to foreign hosts when recursive. -I, --include-directories=LIST list of allowed directories. -X, --exclude-directories=LIST list of excluded directories. -nh, --no-host-...

    Patch for vasp.5.4.4.18Apr17-6-g9f103f2a35

    Fixes a bug in the stress term when using the SCAN functional in certain pathological cases. Fixes a bug in the Thomas-Fermi potential. Fixes a bug that affected the optB88 for some atoms and ...

    XLSReadWriteII.v.5.20.67.D7.D2010-XE10.rar

    One of the major goals with XLSReadWriteII was to create a product that won't corrupt the Excel files and won't alter any data in the file. XLSReadWriteII is easy to use. With the formatting ...

    NextSuite5 v8.2012 Delphi 7 - XE2 Full Source (Aug 8 2012)

    fixed: PageUp key bug when ScrollBar is not visible. fixed: Measuring HTML Column when WrapKid = wkWordWrap. fixed: Bug fixes and internal tweaks. NextGrid v5.7 -- added: RevertStyle(Integer) method....

    windows版curl

    -t, --tries=NUMBER set number of retries to NUMBER (0 unlimits). -O --output-document=FILE write documents to FILE. -nc, --no-clobber don't clobber existing files. -c, --continue restart ...

    Apress.Ansible.From.Beginner.to.Pro.1484216601-182页

    Apress.Ansible.From.Beginner.to.Pro.1484216601-182页 Michael Heap is a polyglot software engineer, committed to reducing complexity in systems and ... When not immersed in technology, you’ll find h

    Android代码-RetrofitUrlManager

    Let Retrofit support multiple baseUrl and can be change the baseUrl at runtime. 中文说明 Overview Notice Framework analysis 1 Framework analysis 2 More complete sample Download implementation 'me....

    FairyGUI-Unity-Plugin-3.4.0.zip

    All shaders are updated, don't forget to replace shaders in your project. - IMPROVED: Text-Brighter mechanism is removed, so FairyGUI-Text-Brighter.shader is removed. - IMPROVED: Add support for ...

    sonar-scanner-cli-4.2.0.1873-macosx.zip

    sonar-scanner4.2 macos版:The SonarScanner is the scanner to use when there is no specific scanner for your build system.

    pkg-config-0.26.tar.gz

    pkg-config is a helper tool used when compiling applications and libraries. It helps you insert the correct compiler options on the command line so an application can use gcc -o test test.c `pkg-...

    FastReport Enterprise v4.15.6 for XE-XE3 installer

    来自于俄罗斯网站,因为CSDN上传文件大小限制,这个是...- fixed duplex problem when printing several copies of the report - fixed problem with PNG images - fixed problem with TfrxPictureView transparent

    Android代码-SimpleTagImageView

    Warning:When you set the round radius,the simpletagimageview scale type just support fitXY now! Usage Quick Start Gradle compile 'net.wujingchao.android.view:simple-tag-imageview:1.0.1' Maven &...

Global site tag (gtag.js) - Google Analytics