2

It's not the first time I have tried to execute a system command from Java; but this time it turns out to be very hard. I have a script that executes just fine from the terminal. It reads input from a file (input.txt), it processes it and exports the result in another file (ouput.txt). The whole thing lasts no more than 1sec. But, when I try to execute it from Java, it gets stuck and never finishes. This is my code:

Process p = new ProcessBuilder("./runCalculator.sh").start();
p.waitFor();

I have also tried with Runtime.getRuntime().exec("./runCalculator.sh") but all the same. I've read both the InputStream and the ErrorStream of the process. The error stream returns nothing but a message like "Starting Calculation..."

Any ideas?

4 Answers 4

4

You need to use the following code:

ProcessBuilder pb = new ProcessBuilder();
pb.command("bash", "-c", "./runCalculator.sh");
Process process = pb.start();
int retValue = process.waitFor();
Sign up to request clarification or add additional context in comments.

2 Comments

Because you have to actually run "bash" (or "sh"), which is the interpreter. And you pass in the command you would like to execute (for bash this is passed using the -c option)
@Pantelis your original code would have worked if the file that you passed to the ProcessBuilder ctr was an executable file. As it was the shell script runCalculator.sh a shell (bash or sh) is the executable program file required to interpret the shell script commands and run them. At the command line run $file /usr/bin/bash and compare the output to running $file ./runCalculator.sh
3

You likely need to invoke the unix command interpreter/processor for this to work. Please see: When Runtime.exec() won't.

Comments

3

Try this:

Process p = new ProcessBuilder("sh ./runCalculator.sh").start();

Comments

0

Another, simplier solution is that you can open program by entering the name of the program (this assumes that program is installed) instead of creating script and calling it.

Note that the name of the program isn't always what you see in Gnome's menu, for example Gnome's calculator is "gnome-calculator".

Regarding this facts, you can run calculator by the folowing line:

Process p = Runtime.getRuntime().exec("gnome-calculator");

In that case you don't have a need for any sh scripts (in your case runCalculator.sh).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.