问题
I am trying to execute an sh file via the following code (CentOS machine btw)
Runtime.getRuntime().exec("sh " + file.getPath());
I use this code for windows and it works fine
Runtime.getRuntime().exec("cmd /c start " + file.getPath());
Could it be because I'm using Screen in the .sh file? I am also using the java command to start the server so maybe I need to include these?
Here are the contents of the sh file
#!/bin/sh
BINDIR=$(dirname "$(readlink -fn "$0")")
cd "$BINDIR"
screen -S PrivateServer java -Xms2048M -Xmx2048M -jar somejar.jar -o true
I am also running this code from a shutdown hook, could this be the issue? This is intended because the software is a game server and it is intended so that the user can use a restart command or have it auto restart without needing to setup anything them self.
Edit: I decided to output the errors to a text file and found this "Must be connected to a terminal." any ideas? I believe this is an issue to do with using screen.
回答1:
Since you confirmed that the file has executable permission, try to pass the argument as follows:
Runtime.getRuntime().exec(new String[]{"/bin/sh" ,"-c", file.getPath()});
So mainly provide the complete path for sh
and use -c
回答2:
Yo need to set the permissions for the operation, usually the "sh" files require execution permission in order to run this scripts from a Java Application. You must run the Java application as root (sudo su) or sudo java -jar. Or set full access to your script "sudo chmod 777 ..." well, not full access, but at least chmod +x for any user that wants to execute your script.
Best regards.
回答3:
I recommend using org.apache.commons.exec.* to run such.
回答4:
It does not seem to have executable permissions, try executing "chmod +x shell_script_filename"
before executing the shell script
来源:https://stackoverflow.com/questions/14987214/execute-sh-file-from-java