“exec Kill -SIGINT”後 shellscript 崩潰的問題

“exec Kill -SIGINT”後 shellscript 崩潰的問題

我修改了在這裡找到的 shell 腳本: https://github.com/Slympp/ConanLinuxScript

但我在使用“conan_stop”函數時遇到了麻煩 該腳本在之後終止

exec kill -SIGINT $pid

該腳本成功發送了終止命令,但之後它就終止了,沒有錯誤代碼或任何內容。

腳本中的所有變數均在文件的前面定義。

功能齊全

function conan_stop {

pid=$(ps axf | grep ConanSandboxServer-Win64-Test.exe | grep -v grep | awk '{print $1}')

if [ -z "$pid" ]; then
        echo "[$(date +"%T")][FAILED] There is no server to stop"
else
    if [ "$discordBotEnable" = true ]; then
        echo "[$(date +"%T")][SUCCESS] Discord bot is enabled"
        if [ -n "$botToken" ] && [ -n "$channelID" ]; then
            secLeft=$(($delayBeforeShutdown * 60))

            while [ $secLeft -gt "0" ]; do
                minLeft=$(($secLeft / 60))
                echo "[$(date +"%T")][WAIT] Server will be shut down in $minLeft minutes"
                python3 $discordScript $botToken $channelID "Servern kommer stängas ner om " $minLeft "minuter."
                secLeft=$(($secLeft - 60))
                sleep 60
            done
            python3 $discordScript $botToken $channelID "Servern stängs nu ner."
        else
            echo "[$(date +"%T")][ERROR] No Discord botToken or channelID found"
        fi
    fi

        echo "[$(date +"%T")][SUCCESS] Existing PIDs: $pid"
        exec kill -SIGINT $pid

        isServerDown=$(ps axf | grep ConanSandboxServer-Win64-Test.exe | grep -v grep)
        cpt=0
        while [ ! -z "$isServerDown" ]; do
                echo "[$(date +"%T")][WAIT] Server is stopping..."
                ((cpt++))
                sleep 1
                isServerDown=$(ps axf | grep ConanSandboxServer-Win64-Test.exe | grep -v grep)
        done
        echo "[$(date +"%T")][SUCCESS] Server stopped in $cpt seconds"

        if [ "$discordBotEnable" = true ]; then
                echo "[$(date +"%T")][SUCCESS] Discord bot is enabled"
                if [ -n "$botToken" ] && [ -n "$channelID" ]; then
                        python3 $discordScript $botToken $channelID "Servern stängdes ner efter $cpt sekunder."
                else
                        echo "[$(date +"%T")][ERROR] No Discord botToken or channelID found"
                fi
        fi
fi

}

答案1

exec更換外殼使用給定的命令,如exec()係統呼叫。當命令(kill此處的 )停止時,shell 不再存在,因此腳本無法繼續。

這兩個例外是 1) 當exec給出重定向時,在這種情況下它只將它們應用到當前 shell 中,以及 2) 當命令無法執行時,在這種情況下exec會給出錯誤並返回錯誤的退出代碼。

所以,exec kill ...幾乎與 相同kill ... ; exit。不完全相同,但在本例中足夠接近。

相關內容