java - 从 java 运行 shell 脚本 - 未完成任务

标签 java shell runtime

我有一个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/

相关文章:

algorithm - 对这些渐近符号及其运行时感到困惑

Excel VBA 用户窗体动态运行时控件 - 跨多个控件触发相同类事件

java.util.NoSuchElementException - 扫描仪读取用户输入

java - 如何从 Maven 项目中的 pom.xml 中排除已签名的 jar

bash - 如何从 bash 中读取整行

shell - zsh zle 移位选择

c - 我的代码中有一个运行时错误,我需要分析

java - 如何在不使用 InheritableThreadLocal 的情况下为每个顶级进程/线程提供共享上下文?

java - 继承类中的构造函数调用

linux - 我在 bash 代码中使用 awk 语句时遇到一些困难