从java代码运行shell脚本

57hvy0tb  于 12个月前  发布在  Shell
关注(0)|答案(4)|浏览(123)

我有一个运行bash文件的java应用程序,在bash文件中,我有一个运行另一个java应用程序的代码,它似乎不起作用。我来自c++,这是一个非常容易的任务,但我对java没有真正的经验。下面是我的代码:

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();
}

}

这是我的bash文件:

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

下面是这段代码的结果:
我是主..脚本执行..
我知道“Script executed..”不应该打印出来,因为我试图从bash文件运行的java文件是一个无限循环。

注: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.

我希望我说得很清楚,如果没有,请询问更多信息。谢谢

eufgjt7s

eufgjt7s1#

另一种方法是使用Runtime.getRuntime()。这样的事情

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);
    }
}
dluptydi

dluptydi2#

通过以上测试,您无法保证它是否正在运行。因为很明显,你告诉你在第二个Java应用程序中运行一个无限循环。现在我的建议是在无限循环中放入一些System.out.println语句,并使用下面的java代码来执行shell脚本。在output.txt文件中,你可以看到shell脚本和java程序的输出,你将知道应用程序是否成功执行。在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();
    }
p1iqtdky

p1iqtdky3#

你也可以使用我的小库jaxec

import com.yegor256.Jaxec;
String stdout = new Jaxec("script.sh")
    .withHome("/home/me") // run it in this directory
    .withRedirect(false) // don't redirect STDERR to STDOUT
    .exec();

Jaxec类不仅会执行shell命令,还会将其输出发送到Slf4j log,等待其完成,将stderr重定向到stdout,并确保在退出代码不等于零时引发异常。

cuxqih21

cuxqih214#

如果你像写Process p = pb.start();那样启动一个进程,它会从java进程中多创建一个进程(我们通常说fork)。
1.例如,java作为进程'A'运行
1.如果进程“A”启动另一进程“B”,
1.那么它们是同时运行的。
(in你的情况下,A是'JAVA'和B是'Shell')
所以是2这两个进程同时(并行)运行,因此您将同时获得其中两个结果。

相关问题