|
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;
} |
|
|
|
|
|
|