使用shell腳本寫(xiě)一個(gè)守護(hù)進(jìn)程,監(jiān)聽(tīng)3003端口,是否有被使用,若沒(méi)有,則開(kāi)啟
#!/bin/sh
cmd=$1
port=3003
if [ -n "$cmd" ]
then
# 守護(hù)進(jìn)程[ nohup sh run.sh 1 & ]
while true
do
sleep 3;
# 根據(jù)端口號(hào)查詢(xún)對(duì)應(yīng)的pid
pid=$(netstat -nlp|grep :$port|awk '{print $7}'|awk -F"/" '{ print $1 }')
# 如果pid不存在,則啟動(dòng)進(jìn)程
if [ ! -n "$pid" ];then
# echo "開(kāi)啟npm run start"
nohup npm run start > /var/log/web/user.log 2>&1 & continue
fi
# echo '進(jìn)程守護(hù)中......'
done
else
# 重啟進(jìn)程[ sh run.sh]
# 根據(jù)端口號(hào)查詢(xún)對(duì)應(yīng)的pid
pid=$(netstat -nlp|grep :$port|awk '{print $7}'|awk -F"/" '{ print $1 }')
#殺掉對(duì)應(yīng)的進(jìn)程,如果pid不存在,則不執(zhí)行
if [ -n "$pid" ];then
kill -9 $pid
echo "殺掉已有進(jìn)程ID: ${pid}"
echo "重新執(zhí)行npm run start..."
nohup npm run start > /var/log/web/user.log 2>&1 & exit
else
echo "開(kāi)啟npm run start"
nohup npm run start > /var/log/web/user.log 2>&1 & exit
fi
fi