`
junge8618
  • 浏览: 117988 次
  • 性别: Icon_minigender_1
  • 来自: 邵阳
社区版块
存档分类
最新评论

ShellCommand_Java代码中执行shell脚本_Process的输入、输出、错误流都需要关闭。

阅读更多
Java代码中执行shell脚本_Process的输入、输出、错误流都需要关闭否则会报IO异常:too many open files.

正确的代码应该这样写:
public static int executeWithExitValue(String shellFile)
    {
        
        //脚本文件为NULL或空值
        if (null == shellFile || shellFile.equals(""))
        {
            logger.warn("ShellCommand shellFile is null.");
            return -1;
        }
        
        if (logger.isDebugEnabled())
        {
            logger.debug("bash " + shellFile);
        }
        
        Process process = null;
        int exitValue = 1;
        try
        {
            process = Runtime.getRuntime().exec("bash " + shellFile);
            process.waitFor();
            
            exitValue = process.exitValue();
            
            if (logger.isDebugEnabled())
            {
                logger.debug("the exit value of script is " + exitValue);
            }
        }
        catch (Exception e)
        {
            logger.error("Execute " + shellFile + " exception:", e);
        }
        finally
        {
            if (null != process)
            {
                try
                {
                    process.getErrorStream().close();
                }
                catch (IOException e)
                {
                    logger.error("close error stream of process fail.", e);
                }
                finally
                {
                    try
                    {
                        process.getInputStream().close();
                    }
                    catch (IOException e)
                    {
                        logger.error("close input stream of process fail.", e);
                    }
                    finally
                    {
                        try
                        {
                            process.getOutputStream().close();
                        }
                        catch (IOException e)
                        {
                            logger.error(
                                    "close output stream of process fail.", e);
                        }
                    }
                }
                
            }
            
        }
        
        if (logger.isDebugEnabled())
        {
            logger.debug("end invoke function checkStatus.");
        }
        return exitValue;
    }
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics