ubuntu创建守护进程,并设置开机自启动(rc.locla,rc_local.sercive)

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、试试看是否成功

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值