http://www.davidpashley.com/articles/writing-robust-shell-scripts/
I created two reusable bash functions to implement race conditions safe locks:
################################################################################
me=${0##*/}
lockfile="/var/lock/${me}" # WARNING ! On AIX lock files are in /var/locks/ (note the s)
now() {
echo `date +%Y%m%d.%H%M%S`
}
lock() {
waitsecs=$1 # set to "" to have an empty value while being able to set next parameters
maxtries=$2 # set to 0 to retry undefinetively
warning=$3 # set to anything to have a warning on standard output
try=0
while true ; do
if ( set -o noclobber ; echo "$$" > "$lockfile") 2> /dev/null ; then
trap 'rm -f "$lockfile" ; exit $?' INT TERM EXIT
return 0
else
[ ! -z $warning ] && echo "`now`: Failed to acquire lockfile, it's held by pid $(cat $lockfile)"
if [ ! -z $waitsecs ] ; then
try=$((try+1))
[ ${try} -eq ${maxtries} ] && exit 3 || sleep $waitsecs
else
exit 3
fi
fi
done
}
unlock() {
rm -f "$lockfile"
trap - INT TERM EXIT
}
lock "" 0 yes
# lock 60 5
# lock 1 60 yes
# critical section
unlock
################################################################################
1 commento:
grazie mille, mi sei stato d' aiuto come non mai
Posta un commento