前言
最近在玩很小型的系统,一般都不使用systemd
而是很古老的systemV
管理进程
为了让我的进程保持开启,我决定研究这个linux启动模式
脚本
一个脚本通常由service
命令来管理
如以下一个frp脚本,路径为/etc/rc.d/init.d/frps
#!/bin/sh
. /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
|
这个脚本用于管理frps的启动/停止/重启,很明显这是一个以sh命令运行的脚本,用法为
service frps start|stop|restart
在脚本的最开始还有
. /etc/sysconfig/rc
. ${rc_functions}
这是运行了对应目录的脚本
/etc/sysconfig/rc
中定义了rc_functions
可以让此脚本调用别的脚本的函数
守护进程
事实上单凭这样没办法实现守护进程,也就是无法处理frp异常退出的情况
如果要处理这种情况必须再来一个脚本监控frp的PID,如以下脚本
#!/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” ]判断也是一样的