“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。不完全相同,但在本例中足够接近。

相关内容