Jar完成后退出流程

时间:2014-01-08 05:21:11

标签: java shell processbuilder exit-code

我正在使用流程构建器在我的Java程序中使用shell脚本执行我的Runnable Jar。 下面是我的Java代码

 command = "t4essh -l " + username +  " -p " + password + " -a 2500 -A password " + host + " \" cd " +"/data/jblext/JBLOADER.OUT" +";./test.sh "+tablename+" \"";
         Runtime rtt = Runtime.getRuntime();
          Process pr = rtt.exec(command);
          OutputStream obj = pr.getOutputStream();

            ByteArrayOutputStream byte1=new ByteArrayOutputStream();  
            obj.write(byte1.toByteArray());  
            String s=byte1.toString();  
                  System.out.println("output from .sh " + s);


          System.out.println("command"+ command);
          boolean processFinish = false;

             while(!processFinish) {
                 try {
                    Thread.sleep(500);
                     int exitVal = pr.exitValue();
                     System.out.println("Process"+exitVal);
                     System.out.println("Process exitValue: " + exitVal);

                     if (exitVal == 0)

                         {System.out.println("testet");
                         processFinish = true;}

                     else
                     {System.out.println("sysysyyyyyyyy");
                         processFinish = false;
                     }

                 } catch (Throwable t) {
                     processFinish = false;
                     System.out.println("catch"+ t);
                    /* GENERAL.println("Waiting for process finish : " + command);
                     System.out.println("Waiting for process finish : " + command);*/
                    // t.printStackTrace();
                 }

             }
 }
             catch (Exception e) {
                  BufferedWriter bw = null;
                    System.err.println("Error executing parse command " + e.getMessage());

             }

我在Linux服务器上安装了我的shell脚本。下面是一段代码

#!/bin/sh
echo "test"
java -jar Manager.jar $1 

当我用

执行我的java程序时
catchjava.lang.IllegalThreadStateException: process has not exited   

My Runnable jar将运行至少2分钟。一旦runnable jar完成,我该如何退出?

2 个答案:

答案 0 :(得分:0)

System.exit()退出整个系统,而不是当前进程。 我认为,有两种常用方法可以退出当前流程(我的意思是Method)。

1. Use `return`
2. Use `throw Exception`

示例:

    public void doSomething() {

        while(your-condition) {
            if(isOK()) {
                throw new Exception(); -> It will exit from doSomething() method;
                throw new MyException(); -> It will exit from doSomething() method;
                return; -> It will exit from doSomething() method;
                break;  -> It will exit while loop;
                System.exit(); -> It will exit from the whole system;
            }
        }
    }

答案 1 :(得分:0)

根据您的评论,您想致电Process.destroy();

pr.destroy(); // <-- this will "kill" the running program...
              // I'm not sure what it did to you.