I'm trying to execute a shell script in a Java program using ProcessBuilder
. The problem is that my Java program hangs itself/freezes every time I use the ProcessBuilder to run the script. Upon executing the shell script, the terminal window in the Java program hangs and to close down the program, I need to kill the process with kill -9 PID
, I can simply not close down the program with the exit
command in the terminal which I can in normal cases when it's not frozen.
By looking at the active running processes on the Linux server after I've ran the test, both my Java program, the shell script it executes, and the 2nd Java program that the executing shell script start are all 3 active, hence 1st Java program (the one using ProcessBuilder) still being frozen.
I have also set the ProcessBuilder to redirect the error stream to a file but that file is completely empty every time after each run.
Java Code
public static void main(String[] args) {
System.out.println("Starting!");
File directory = new File("/path/to");
File startScript = new File(directory, "script.sh");
try {
String command = "sh " + startScript.getAbsolutePath();
System.out.println("Path set to: " + startScript.getAbsolutePath());
ProcessBuilder processBuilder = new ProcessBuilder("bash", "-c", command);
processBuilder.directory(directory);
processBuilder.redirectError(new File(directory, "error.txt"));
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
System.out.println("Process start code ran...");
// Exit status
int exitStatus = process.waitFor();
if (exitStatus == 0) {
System.out.println("Test ran successfully!");
} else {
System.out.println("Something went wrong. Exit status is " + exitStatus);
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
Shell Script
#!/bin/bash
echo "Starting..."
cd /path/to/
java -Xms2G -Xmx2G -jar /path/to/server.jar nogui
Terminal Output of "main" Java Program
Path set to: /the/path/script.sh
Process start code ran...
Tried
I have tried the code showed above multiple times with multiple different commands (for example I have tried the command in the ProcessBuilder
simply being the path to the script, still the same result).
Expected The start script to execute without errors and the Java program to still function properly after that. I also expect that the terminal should output the "Test ran successfully!" or "Something went wrong. Exit status is X.", something it does not do.
Happened The program hangs itself after reaching the "Process start code ran...". The shell script gets executed as can be seen in the running processes list.