Sample Header Ad - 728x90

Does pid file work by assuming pid is not usable?

0 votes
0 answers
612 views
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.
Asked by Tim (106420 rep)
Oct 30, 2018, 06:17 PM