用于运行shell脚本的Java代码,该脚本又运行另一个脚本

时间:2016-09-22 12:10:12

标签: java linux bash shell processbuilder

我已经在本论坛或网络上提出了各种类似的问题,但没有一个符合我在下面解释的情况。基本上我需要从Java运行shell脚本。以下是我的代码:

$ HOME_FOLDER

生成

#!/bin/sh
----- various commands -----
java com.test.web.RestApplication --server.port=9090

start.sh

#!/bin/sh
cd $HOME_FOLDER
nohup ./run &

stop.sh

#!/bin/sh
pkill -f RestapiApplication
cd $HOME_FOLDER
rm -fr nohup.out

在其他文件夹中

RunShellScript.java

public class RunShellScript
{
    public static void main(String[] args)
    {
            String enVar = System.getenv("HOME_FOLDER");
            String command = "";
            String option = args[0];
            switch(option){
                    case "start": command += enVar+"/start.sh";
                                    break;
                    case "stop": command += enVar+"/stop.sh";
            }
            try{
                    ProcessBuilder pb = new ProcessBuilder("/bin/bash","-c",command);
                    Process p = pb.start();
                    p.waitFor();
                    int shellExitStatus = p.exitValue();
                    System.out.println(shellExitStatus);
            }catch(Exception e){
                    e.printStackTrace();
            }
    }
}

我能够从上面的代码中成功执行 stop.sh (杀死服务并删除nohup.out)但不能 start.sh (基本上运行)我的春靴服务)。两种情况下的退出值均为0。当尝试从上面的java代码运行 start.sh 时,甚至不创建存储 run 脚本输出的 nohup.out 文件。从命令行(./start.sh)运行时, rd_start.sh 正常运行。在这方面有什么帮助吗?谢谢。

0 个答案:

没有答案
相关问题