Java simple process builder issue

随声附和 提交于 2021-01-29 04:47:00

问题


I just conducted simple test code for Java Process Builder. There are 4 examples and everything is working smoothly excluding last one. Here is my codes

public class bashProcessor {

public static void main(String args[]) {
try {
  ProcessBuilder pb;

  pb = new ProcessBuilder("/bin/bash", "-c", "touch Jin_1.sh");
  pb.start();

  pb = new ProcessBuilder("/bin/bash", "-c", "mkdir Jin_2");
  pb.start();

  pb = new ProcessBuilder("/bin/bash", "-c", "bash /home/Jin/test.sh");
  pb.start();

  //below is not working
  pb = new ProcessBuilder("/bin/bash", "-c",
      "bash /home/solr-tomcat/bin/shutdown.sh warm4 solr-instances");

  pb.start();

  System.out.println("pb job is done now");

  Thread.sleep(3000);

} catch (Exception e) {
  System.out.println(e.getMessage());
}
 }
 }

When I type last example(bash /home/solr...) by hand-typing. It works without any error. I need your kind help. if you have any idea please let me know it would be great help.


回答1:


As pointed out by @ug_ try to remove bash from command and then execute your code. Following code works fine with multiple command.

cmd.java

import java.io.BufferedReader;
import java.io.InputStreamReader;
public class cmd {
    public static void main(String[] args) {
       try {
                String[] command = new String[3];
                command[0] = "/bin/bash";
                command[1] = "-c";
                command[2] = "javac -verbose HelloWorld.java";


                Process p = Runtime.getRuntime().exec(command);
                BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
                BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                String Error;

                while ((Error = stdError.readLine()) != null) {
                    System.out.println(Error);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }       
    }
}

HelloWorld.java

public class HelloWorld {
    public static void main(String[] args) {
       System.out.println("Hello World");
    }
}


来源:https://stackoverflow.com/questions/35837355/java-simple-process-builder-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!