Featured image of post UNIX System V系统用shell实现守护进程

UNIX System V系统用shell实现守护进程

UNIX System V系统用shell实现守护进程管理

前言

最近在玩很小型的系统,一般都不使用systemd而是很古老的systemV管理进程

为了让我的进程保持开启,我决定研究这个linux启动模式

脚本

一个脚本通常由service命令来管理

如以下一个frp脚本,路径为/etc/rc.d/init.d/frps

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
##!/bin/sh
#########################################################################
## Begin $rc_base/init.d/
##
## Description :
##
## Authors     :
##
## Version     : 00.00
##
## Notes       :
##
#########################################################################

. /etc/sysconfig/rc
. ${rc_functions}

FRPS_BIN="/etc/frp/frps"

FRPS_CONFIG="/etc/frp/frps.ini"
case "$1" in
    start)
        echo "Starting frps"
        $FRPS_BIN -c $FRPS_CONFIG
        ;;
    stop)
        echo "Stopping frps"
        pkill -f "$FRPS_BIN"
        ;;
    restart)
        echo "Restarting frps"
        pkill -f "$FRPS_BIN"
        sleep 1
        $FRPS_BIN -c $FRPS_CONFIG
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
        ;;
esac
## End $rc_base/init.d/

这个脚本用于管理frps的启动/停止/重启,很明显这是一个以sh命令运行的脚本,用法为

service frps start|stop|restart

在脚本的最开始还有 . /etc/sysconfig/rc . ${rc_functions}

这是运行了对应目录的脚本

/etc/sysconfig/rc中定义了rc_functions

可以让此脚本调用别的脚本的函数

守护进程

事实上单凭这样没办法实现守护进程,也就是无法处理frp异常退出的情况

如果要处理这种情况必须再来一个脚本监控frp的PID,如以下脚本

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
##!/bin/sh
function myecho(){
    date=$(date)
    echo $date $1
}
PROG="frps"
while [ 1 -eq 1]
do
pid=$(/bin/ps | /bin/grep $PROG | /bin/grep -v grep | /bin/sed -n 's/^\s*\s*\([0-9]\+\).*/\1/p')
myecho "checking sshfs status..."
if [ -z "$pid" ]
then
    myecho "$PROG is not running."
    service $PROG start
    myecho "$PROG start."
else
    myecho "$PROG is running now."
    sleep 5m
fi
done

我这里使用的是ps grep sed查询pid,你也可以将pid写在文件里,然后直接PID=ps -ef|grep $PID,并且使用if [ -z “$PID” ]判断也是一样的