linux下编写简单的守护进程

时间:2022-06-01 15:23:48

搭建linux服务器的时候,需要写一个简单的守护进程来监控服务的运行情况,shell脚本如下:

#!/bin/sh

function daemon()
{
while true
do
server=`lsof -i:` #服务器占用端口为8080,通过查看8080端口是否占用来判断服务是否启动
date=`date "+%Y-%m-%d %H:%M:%S"`
if [ ! "$server" ]
then
echo "$date, webserver is stoped!"
nohup sh startserver.sh >> nohup.out >& & #通过nohup命令后台运行服务
echo "$date, webserver is starting..."
sleep #启动后等待10s
else
echo "$date, webserver is running..."
fi
sleep
done
} daemon

存为monitor.sh,通过nohup ./monitor.sh >> monitor.log 2>&1 & 来启动。