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:
#!/bin/bash
mkdir -p "$HOME/tmp"
PIDFILE="$HOME/tmp/myprogram.pid"
if [ -e "${PIDFILE}" ] && (ps -u $(whoami) -opid= |
grep -P "^\s*$(cat ${PIDFILE})$" &> /dev/null); then
echo "Already running."
exit 99
fi
/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.
Thanks.
ps | grep
looks awkward. Consider using a lock directory rather than a lock file. See e.g. unix.stackexchange.com/questions/401415/…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