如何正确处理服务脚本中pid.file的删除

zel*_*lla 5 linux shell pid shell-scripting

我正在尝试为应用程序编写服务脚本。所以我可以这样控制它:

./myscript.sh start|stop|status
Run Code Online (Sandbox Code Playgroud)

启动时pid.file创建进程 ID,并基于它我可以检查状态并停止进程。在停止命令中我删除了pid.file- 没关系。

但是,如果应用程序以异常方式崩溃 - 关闭电源等,则pid.file不会删除,我需要手动删除它。

如何在脚本中正确处理这种异常情况?

gle*_*man 2

您可以验证 pid 是否正在运行并且属于您的应用程序:

pid=$(< "$pidfile")   # a bash builtin way to say: pid=$(cat $pidfile)
if  kill -0 $pid &&
    [[ -r /proc/$pid/cmdline ]] && # find the command line of this process
    xargs -0l echo < /proc/$pid/cmdline | grep -q "your_program_name"
then
    # your application is running
    true
else
    # no such running process, or some other program has acquired that pid:
    # your pid file is out-of-date
    rm "$pidfile"
fi
Run Code Online (Sandbox Code Playgroud)