To use a pid file for ensuring singleton running instance of a program, I thought that when a process finishes running the program, it should remove the pid file, until I know it doesn't when reading https://stackoverflow.com/a/7453411/156458:


mkdir -p "$HOME/tmp"

if [ -e "${PIDFILE}" ] && (ps -u $(whoami) -opid= |
                           grep -P "^\s*$(cat ${PIDFILE})$" &> /dev/null); then
  echo "Already running."
  exit 99

/path/to/myprogram > $HOME/tmp/myprogram.log &

echo $! > "${PIDFILE}"
chmod 644 "${PIDFILE}"

Here's how it works: The script first checks to see if the PID file exists ("[ -e "${PIDFILE}" ]". If it does not, then it will start the program in the background, write its PID to a file ("echo $! > "${PIDFILE}""), and exit. If the PID file instead does exist, then the script will check your own processes ("ps -u $(whoami) -opid=") and see if you're running one with the same PID ("grep -P "^\s*$(cat ${PIDFILE})$""). If you're not, then it will start the program as before, overwrite the PID file with the new PID, and exit. I see no reason to modify the script

Does the above script assume that no pid is recycled?

Can it happen that a process finishes running the program, and its pid is reused by a new process running a different program? In such a case, the quoted script will falsely think that a process is running the program.


  • 1
    That piece of code is flawed in several ways, and not removing the PID file is just one of them. There are also race conditions, and that ps | grep looks awkward. Consider using a lock directory rather than a lock file. See e.g. unix.stackexchange.com/questions/401415/… – Kusalananda Oct 30 '18 at 18:24
  • I originally thought that ensuring singleton instance of running a program is based on testing existing of a lock file, or someway entirely dependent on the lock files. When I read that reply and also another reply using flock, I found that both ways don't remove the lock files. Is removing a lock file not recommended in general? I also asked if we can tell if a process is running a program by only looking at the lock file unix.stackexchange.com/q/478712/674 – Tim Oct 30 '18 at 18:32
  • related on SO: Are PID-files still flawed when doing it 'right'? – sebasth Oct 30 '18 at 18:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.