5

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?

zella
  • 153
  • 1
  • 1
  • 5

2 Answers2

2

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
Magne
  • 103
  • 4
glenn jackman
  • 4,630
  • 1
  • 17
  • 20
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/.