简体   繁体   English

从Java执行sh文件

[英]Execute sh file from Java

I am trying to execute an sh file via the following code (CentOS machine btw) 我正在尝试通过以下代码执行sh文件(CentOS计算机btw)

Runtime.getRuntime().exec("sh " + file.getPath());

I use this code for windows and it works fine 我将此代码用于Windows,并且工作正常

Runtime.getRuntime().exec("cmd /c start " + file.getPath());

Could it be because I'm using Screen in the .sh file? 可能是因为我在.sh文件中使用Screen吗? I am also using the java command to start the server so maybe I need to include these? 我也使用java命令启动服务器,所以也许我需要包括这些?

Here are the contents of the sh file 这是sh文件的内容

#!/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. 我相信这与使用屏幕有关。

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. 您需要设置操作权限,通常,“ sh”文件需要执行权限才能从Java应用程序运行此脚本。 You must run the Java application as root (sudo su) or sudo java -jar. 您必须以root用户(sudo su)或sudo java -jar运行Java应用程序。 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. 或将对脚本“ sudo chmod 777 ...”的完全访问权限设置为完全访问,而不是完全访问,但对于要执行脚本的任何用户,至少要使用chmod + x。

Best regards. 最好的祝福。

我建议使用org.apache.commons.exec。*来运行。

它似乎没有可执行权限,请在执行外壳程序脚本之前尝试执行"chmod +x shell_script_filename"

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 因此主要提供sh和use -c的完整路径

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM