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

     原文比较长,在这里就不转载了,给出地址: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中,所以这些调用没有问题,否则就要写绝对路径) 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值