用shell寫(xiě)一個(gè)守護(hù)進(jìn)程腳本

使用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


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請(qǐng)通過(guò)簡(jiǎn)信或評(píng)論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容