我有一个Java程序,应该启动一个Shell脚本。该脚本包含6个任务,这些任务将按顺序执行。 Java程序启动脚本并启动(如我所看到的日志)。但是,在10到15秒后,即使在shell脚本中的第一个任务完成之前,执行也会停止。奇怪的是,当我在终端中启动脚本时,脚本运行良好。为避免在执行脚本时冒程序挂起的风险,我在单独的线程中启动它。可能是什么原因?
Java代码-
try {
log.info("run cmd - "+optionsRun);
String[] cmdLine = (String[]) optionsRun.toArray(new String[optionsRun.size()]);
Process process = Runtime.getRuntime().exec(cmdLine);
log.info("end run cmd " + this.getScriptPath());
//
// BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
// writer.write("mypwd");
// writer.flush();
// writer.close();
InputStream is = process.getErrorStream();
String error = inputStreamToStringValue(is);
log.trace("Eventual error was : " + error);
InputStream os = process.getInputStream();
String output = inputStreamToStringValue(os);
log.info("Eventual output was : " + output);
if (error!=null & error.length()>0) {
throw new ActionProcessingException("An error occurred when running the script :'"+this.getScriptPath()+"' with following error message : "+error);
}else {
log.info("Script run ended successfully.");
}
Shell脚本看起来像这样-
#!/bin/sh
# ./publish <path-to-publish-home-folder> <workspace_id> <start_date> <end_date>
# ./publish <path-to-publish-home-folder> 100011 2010-01-06-12:00:00-CET 2012-01-14-19:00:00-CET
rm -f $1/publish.log
echo 'Start publish' >> $1/publish.log
echo $0 $1 $2 $3 $4 $5 $6 $7 $8 $9 >> $1/publish.log
# lancement de l'export RDF du domaine
cd $1/1-export-domain
echo "Starting export domain with the command - ./export.sh $2" >> $1/publish.log
./export.sh $2
# lancement de l'export des translations du domaine
cd $1/2-export-trans
echo "Starting export domain(translated) with the command - ./export.sh $2" >> $1/publish.log
./export.sh $2
.....
.....
a couple of more steps like 1 and 2
....
提前致谢,
最佳答案
我不确定,但是我会推荐两个链接,它们可能会帮助您弄清楚。
第一个是关于Runtime.exec()
的非常古老的:
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
第二个是关于ProcessBuilder
的,新类旨在替换Runtime.exec()
:
http://www.java-tips.org/java-se-tips/java.util/from-runtime.exec-to-processbuilder.html