Skip to content

Instantly share code, notes, and snippets.

@tsopokis
Created August 29, 2018 10:33
Show Gist options
  • Save tsopokis/bfc2b647ea14d5b0cc5cdf6d1593ce3b to your computer and use it in GitHub Desktop.
Save tsopokis/bfc2b647ea14d5b0cc5cdf6d1593ce3b to your computer and use it in GitHub Desktop.
Bash Script PID file locking with extra care trying to avoid simultaneous runs using a random backoff
#!/bin/bash -
set -e
scriptname=$(basename $0)
pidfile="/tmp/${scriptname}.pid"
if [ -d /var/run ] && [ -w /var/run ]; then
pidfile="/var/run/${scriptname}.pid"
fi
if [ -f $pidfile ]; then
pid=$(cat $pidfile)
# lets try to avoid simultaneous start by random backoff
random=$(od -A n -t d -N 1 /dev/random); random=$(( 1 + $random % 6 ))
running=1
ps -eo pid,command | grep "^$pid.*${scriptname}" > /dev/null 2>&1 || running=0
if [ $running -eq 0 ]; then
echo $$ > $pidfile
sleep $random
fi
pid=$(cat $pidfile)
if [ $$ -ne $pid ]; then
running=1
ps -eo pid,command | grep "^$pid.*${scriptname}" > /dev/null 2>&1 || running=0
if [ $running -eq 1 ]; then
echo "[PID $$]: ${scriptname} already running with pid ${pid}. Exiting."
exit 1
fi
fi
fi
echo $$ > $pidfile
if [ $? -ne 0 ]; then
echo "Could not create PID file ${pid}"
exit 1
fi
### main script ###
echo Main [$$]
while [ 1 -eq 1 ]; do
sleep 20;
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment