created on | January 18, 2022 |
homegrown solutions
locking with lock file
lockfile=/var/lock/proc$$.lock
if ( set -o noclobber; echo "$$" > ${lockfile} ) 2> /dev/null; then
trap 'rm -f ${lockfile}; exit $?' INT TERM EXIT
# do stuff here
# clean up and release your trap
rm -f ${lockfile}
trap - INT TERM EXIT
else
printf "lock exists: %s owned by process %s" ${lockfile} $(cat ${lockfile})
fi
locking with hard links
hard links are atomic over NFS
lockfile=/var/lock/proc-whatever.lock
tmpfile=${lockfile}.tmp
echo $$ > ${tmpfile}
if ln ${tmpfile} ${lockfile} 2>&-; then
printf "locked"
else
printf "locked by %s" $(<${lockfile})
rm ${tmpfile}
exit
fi
trap "rm ${tmpfile} ${lockfile}" 0 1 2 3 15
# do what you need to
dotlockfile
tbd …
references
Wikipedia Atomic operations on NFS
StackExchange Correct locking in shell scripts?
PHP documentation flock