关于Runtime.getRuntime().exec()的安全性

来源:互联网 发布:三维动画用什么软件 编辑:程序博客网 时间:2024/05/16 01:48
 public  boolean exeCommand(String cmd, String msg) {
        log.debug(cmd);
        Process process 
= null;
        
try {
            String[] cmdary 
= {"cmd""/C", cmd};
            process 
= Runtime.getRuntime().exec(cmdary);
            StreamGobbler errorGobbler 
= new StreamGobbler(process.getErrorStream(), "Error");
            StreamGobbler outputGobbler 
= new StreamGobbler(process.getInputStream(), "Output");
            errorGobbler.start();
            outputGobbler.start();
             
if (errorGobbler.is.read() != -1{
                process.destroy();   
//如果出现错误杀掉子进程
                return false;
            }

            
int exitVal = process.waitFor();
            log.debug(
"ExitValue: " + exitVal);   
        }
 catch (Exception e) {
            log.debug(
"execute commond failed :"+msg + " failed " +e);
            process.destroy();   
//如果出现错误杀掉子进程
            return false;
        }

        
return true;
    }
 
class StreamGobbler extends Thread {
    Log log 
= LogFactory.getLog(StreamGobbler.class);
    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"))
                    log.debug(line);
                
else
                    log.debug(line);
            }

        }
 catch (IOException ioe) {
            ioe.printStackTrace();
        }

    }

}

说明:程序运行过程中,如果调用第三软件,在cmd语法正常的情况下,程序也会出现死锁现象,多次这样的运行将会造成吃掉内存,然后系统down行

采用上面的策略,一旦捕获到错误,就跳出来,并将子进程杀掉,这样就能保证程序的运行正常,并不会造成进程的死锁。