我有一个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
关于java - 从 java 运行 shell 脚本 - 未完成任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8464516/