bash 在启动时启动 java 进程并在死亡时自动重启
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2209506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Start java process at boot and auto-restart on death
提问by GregB
I have two requirements for my Java app. If it dies, restart it. If the server reboots, restart it - simple enough. Using the answer hereI have a script that will restart when the java application dies.
我的 Java 应用程序有两个要求。如果它死了,请重新启动它。如果服务器重新启动,重新启动它 - 很简单。使用这里的答案,我有一个脚本,当 Java 应用程序终止时,该脚本将重新启动。
#!/bin/bash
until java -Xms256m -Xmx768m -jar MyApp.jar; do
echo "MyApp crashed with exit code $?. Respawning... " >&2
sleep 5
done
I can run this with "nohup restart_script.sh &" and it will run all day long without issue. Now for the startup requirement. I took the /etc/init.d/crond script and replaced the crond binary with my script but it hangs on startup.
我可以使用“nohup restart_script.sh &”来运行它,它可以毫无问题地运行一整天。现在是启动要求。我使用 /etc/init.d/crond 脚本并用我的脚本替换了 crond 二进制文件,但它在启动时挂起。
#!/bin/bash
#
# Init file for my application.
#
. /etc/init.d/functions
MYAPP=restart_script.sh
PID_FILE=/var/run/myapp.pid
start(){
echo -n "Starting My App"
daemon --user appuser $MYAPP
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && touch /var/lock/subsys/myapp
return $RETVAL
}
stop(){
echo -n "Stopping my application"
killproc $MYAPP
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/myapp
return $RETVAL
}
...
case "" in
start)
start
;;
stop)
stop
;;
...
esac
When I run /sbin/service myapp start the script starts but hangs the console. I have tried "daemon --user appuser nohup $MYAPP &" and I am immediately returned to the prompt without any [OK] indication and when I do a ps, I still see that the init is hung. Any ideas how to call a script within the init script and get it to return properly?
当我运行 /sbin/service myapp start 脚本启动但挂起控制台。我试过“daemon --user appuser nohup $MYAPP &”,我立即返回到提示,没有任何 [OK] 指示,当我执行 ps 时,我仍然看到 init 挂起。任何想法如何在 init 脚本中调用脚本并让它正确返回?
Thanks,
谢谢,
Greg
格雷格
回答by R Samuel Klatchko
The daemon function on my machine (old RedHat) does not return until the executed program returns. So you are going to need to have your little utility script do the forking.
在执行的程序返回之前,我的机器(旧 RedHat)上的守护程序函数不会返回。因此,您将需要让您的小实用程序脚本进行分叉。
Try writing your utility like this:
尝试像这样编写您的实用程序:
#!/bin/bash
(
until java -Xms256m -Xmx768m -jar MyApp.jar; do
echo "MyApp crashed with exit code $?. Respawning... " >&2
sleep 5
done
) &
How this works. Putting a command in parentheses starts code running in a new process. You put the process in the background so the original process will return without waiting for it.
这是如何工作的。将命令放在括号中会启动在新进程中运行的代码。您将进程置于后台,以便原始进程无需等待即可返回。

