简体   繁体   English

从Java代码运行Shell脚本

[英]Run shell script from java code

I have a java app that runs a bash file and inside the bash file i have a code to run another java app and it doesn't seem to work.I come from c++ where this is a very easy task but i'm not really experienced in java. 我有一个运行bash文件的Java应用程序,并且在bash文件中有运行另一个Java应用程序的代码,它似乎无法正常工作。我来自c ++,这是一个非常简单的任务,但我不是真的有Java经验。 So, here's my code: 所以,这是我的代码:

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class start {

public void executeScript(){
    try{
        ProcessBuilder pb = new ProcessBuilder("/root/Desktop/chat/script.sh");
        Process p = pb.start();
        p.waitFor();
        System.out.println("Script executed..");
    }catch(Exception e){
        e.printStackTrace();
        }

}

public static void main(String[] args) {
    start st = new start();
    System.out.println("I'm main..");
    st.executeScript();
}

}

Here's my bash file: 这是我的bash文件:

#!/bin/bash
echo "bash started"
java Client ip_address
echo "bash finished"

Here's the result of this code: 这是此代码的结果:

I'm main.. Script executed.. 我是主..脚本执行..

I know "Script executed.." shouldn't print because the java file i'm trying to run from the bash file is an infinite loop. 我知道不应打印“已执行脚本”,因为我试图从bash文件运行的java文件是一个无限循环。

Note: If i run the bash file separately in the terminal i get an infinite loop which is the intended result and this is why i know that my mistake is from this file. 注意: If i run the bash file separately in the terminal i get an infinite loop which is the intended result and this is why i know that my mistake is from this file.

I hope I made myself clear and if not please ask for more information. 我希望我能说清楚一点,否则请询问更多信息。 Thank you. 谢谢。

Another way of doing would be to use Runtime.getRuntime() . 另一种方法是使用Runtime.getRuntime() Something like this 像这样

  public void executeScript() throws IOException, InterruptedException {
    Process p = Runtime.getRuntime().exec("sh /root/Desktop/chat/script.sh");
    p.waitFor();

    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader errorReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));


    String line = "";
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }

    line = "";
    while ((line = errorReader.readLine()) != null) {
        System.out.println(line);
    }
}

With the above test you can not guaranty that whether it is running or not. 通过以上测试,您无法保证它是否正在运行。 Because clearly you told that your are running a infinite loop inside your second java application. 因为很明显,您告诉您在第二个Java应用程序中正在运行无限循环。 Now my advise would be to put some System.out.println statement inside that infinite loop and use below java code to execute your shell script. 现在,我的建议是将一些System.out.println语句放入该无限循环内,并使用下面的Java代码执行您的Shell脚本。 Here in the output.txt file you can see the output from your shell script as well as java program and you will know whether application executed successfully or not. output.txt文件中,您可以看到shell脚本以及java程序的输出,您将知道应用程序是否成功执行。 Also put some echo statement inside your shell script as well. 还要在您的shell脚本中放入一些echo语句。

 String[] command ={"/root/Desktop/chat/script.sh", "command line param if any"};
    ProcessBuilder pb = new ProcessBuilder(command);

    pb.redirectOutput(new File("/tmp/output.txt"));
    String result;
    String overall="";
    try {
        Process p = pb.start();
        p.waitFor();
        BufferedReader br = new BufferedReader(
                new InputStreamReader(p.getInputStream()));
            while ((result = br.readLine()) != null){
                overall = overall + "\n" + result;
            }
            p.destroy();
            System.out.println(result);

    } catch (Exception e) {
        e.printStackTrace();
    }

if you start a process like you wrote Process p = pb.start(); 如果启动像您编写Process p = pb.start();那样的Process p = pb.start(); it will make(we usually say fork) one more process from the java process. 它将使java进程再增加一个(通常称为fork)进程。

  1. for example, java is running as a process 'A' 例如,java作为进程“ A”运行
  2. and if the process 'A' starts another process 'B' 并且如果进程“ A”开始另一个进程“ B”
  3. then those are running at the same time. 然后它们在同一时间运行。

    (in your case, A is 'JAVA' and B is 'Shell') (在您的情况下,A是“ JAVA”,B是“ Shell”)

so, it will be 2. and the 2 processes are running in the same time (parallely), so you will get two of those results at the same time. 因此,它将是2,并且两个进程同时(并行)运行,因此您将同时获得其中两个结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM