How properly handle deletion of pid.file in service script

12,965

Solution 1

You can verify that the pid is running and belongs to your application:

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

Solution 2

PID files should never be deleted, unless you have uninstalled the software that had created them.

A PID file is primarily a safe-guard against simultaneous execution. Deleting the PID file voids that purpose for good. In the very moment that you unlink the PID file, an arbitrary number of processes may have a on open file descriptor for it and may acquire an exclusive lock on it by the operating system.

The else branch from the answer from @glenn_jackman should really be deleted.

I have explained the underlying problem in greater detail including a code example for reproducing the resulting race conditions at http://www.guido-flohr.net/never-delete-your-pid-file/.

Share:
12,965

Related videos on Youtube

zella
Author by

zella

Updated on September 18, 2022

Comments

  • zella
    zella over 1 year

    I'm trying to write service script for application. So I can control it like this:

    ./myscript.sh start|stop|status
    

    On startup pid.file with process id creates, and based on it I can check status and stop process. In stop command I remove pid.file - it's ok.

    But if application crashes in abnormal way - power off, etc, pid.file not removes and I need remove it manually.

    How to properly handle this abnormal situations in script?