How properly handle deletion of pid.file in service script

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/.