java执行shell脚本超时控制

Java的Runtime可以执行命令行脚本,某些特定场合需要对脚本的执行时间进行控制,防止脚本某些异常情况下,一直未能正确结束,导致Java主进程挂起。本文的程序对这一过程进行了控制

importorg.slf4j.Logger;

importorg.slf4j.LoggerFactory;

importjava.io.BufferedReader;

importjava.io.IOException;

importjava.io.InputStreamReader;

publicclassCommandUtils{

privatestaticLoggerlogger=LoggerFactory.getLogger(CommandUtils.class);

//defaulttimeout,inmillseconds

publicstaticfinalintDEFAULT_TIMEOUT=10*1000;

publicstaticfinalintDEFAULT_INTERVAL=1000;

/**

*Executesthespecifiedcommandinaseparateprocess.Themethodthenblocksuntiltheprocessreturned.

*Ifanerrorarisesduringtheexecutionoriftheexeecutedprocessreturnedannon-nullreturncode,

*thecontentoftheprocess'stderrisreturnedtothecaller.Iftheexecutionisfine,nullisreturned.

*

*@paramcommandString

*@returnCommandResult

*/

publicstaticCommandResultexec(Stringcommand){

longstart=System.currentTimeMillis();

longlast;

CommandResultcommandResult=newCommandResult();

try{

Processprocess=Runtime.getRuntime().exec(command);

process(process,commandResult);

if(process!=null){

process.destroy();

}

last=(System.currentTimeMillis()-start)/1000;

logger.info("Executecommand["+command+"],last["+last+"]s.");

}catch(Exceptione){

last=(System.currentTimeMillis()-start)/1000;

Stringerror="Executecommand["+command+"]last["+last+"]s,failed["+e.getMessage()+"]";

logger.error(error,e);

commandResult.setExitValue(CommandResult.EXIT_VALUE_UNEXCEPTED);

commandResult.setErrorOutput(error);

}

returncommandResult;

}

privatestaticvoidprocess(Processprocess,CommandResultcommandResult){

BufferedReadererrorReader=null;

BufferedReaderinputReader=null;

try{

errorReader=newBufferedReader(newInputStreamReader(process.getErrorStream()));

inputReader=newBufferedReader(newInputStreamReader(process.getInputStream()));

//timeoutcontrol

longstart=System.currentTimeMillis();

booleanprocessFinished=false;

while(System.currentTimeMillis()-start<DEFAULT_TIMEOUT&&!processFinished){

processFinished=true;

try{

process.exitValue();

}catch(IllegalThreadStateExceptione){

//processhasn'tfinishedyet

processFinished=false;

try{

Thread.sleep(DEFAULT_INTERVAL);

}catch(InterruptedExceptione1){

logger.error("Process,failed["+e.getMessage()+"]",e);

}

}

}

if(!processFinished){

commandResult.setExitValue(CommandResult.EXIT_VALUE_TIMEOUT);

commandResult.setErrorOutput("Commandprocesstimeout");

return;

}

commandResult.setExitValue(process.waitFor());

StringBuffersb;

Stringline;

//parseerrorinfo

if(errorReader.ready()){

sb=newStringBuffer();

while((line=errorReader.readLine())!=null){

sb.append(line);

}

commandResult.setErrorOutput(sb.toString());

}

//parseinfo

if(inputReader.ready()){

sb=newStringBuffer();

while((line=inputReader.readLine())!=null){

sb.append(line);

}

commandResult.setInfoOutput(sb.toString());

}

}catch(Exceptione){

Stringerror="Commandprocess,failed["+e.getMessage()+"]";

logger.error(error,e);

commandResult.setExitValue(CommandResult.EXIT_VALUE_UNEXCEPTED);

commandResult.setErrorOutput(error);

}finally{

if(errorReader!=null){

try{

errorReader.close();

}catch(IOExceptione){

logger.error("CloseBufferedReader,failed["+e.getMessage()+"]",e);

}

}

if(inputReader!=null){

try{

inputReader.close();

}catch(IOExceptione){

logger.error("CloseBufferedReader,failed["+e.getMessage()+"]",e);

}

}

}

}

}

相关推荐