1.创建守护进程:
vim protect.sh
sudo chmod +x protect.sh
#!/bin/bash
# 定义所守护的进程名称或关键字
TARGET_PROCESS="java"
while true; do
# 检测目标进程是否运行
if pgrep -x "$TARGET_PROCESS" >/dev/null; then
echo "The process is running."
else
# 启动你的项目运行脚本
/path/to/run.sh &
# 记录守护进程重启的日志
echo "Restarting the project at $(date)" >> daemon_log.txt
fi
# 等待一段时间后重新检测,可以根据需要调整
sleep 10
done
注:为方便开机自启动,建议都写绝对路径,run.sh的也要写绝对路径。
2.rc.local添加开启启动的程序
view /etc/rc.local
sudo chmod +x /etc/rc.local #添加权限
#!/bin/bash
# rc.local
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
# In order to enable or disable this script just change the execution
# bits.
# By default this script does nothing.
# 可以在 exit 0 之前添加需要开机启动的程序
/path/to/protect.sh &
exit 0
3.启动服务
systemctl start rc-local.service
或者
systemctl enable rc-local.service
systemctl status rc-local.service
#看active的状态
#systemctl list-unit-files --type=service | grep "rc-local.service"
4..reboot kill、试试看是否成功