epcim
2/9/2016 - 4:24 PM

bash, paralel execution lock

bash, paralel execution lock


# Alternative 1
# simple approach if $0 is on PATH or if it's executed with full path
exec 200<$0
flock -n 200 ||exit 1


# Alternative 2 (proper)
# uses a lock file under /var/run/
set -e # exit on errors
scriptname=$(basename $0)
pidfile="/var/run/${scriptname}"
exec 200>$pidfile
flock -n 200 || exit 1
pid=$$
echo $pid 1>&200

# your code 
# ...