避免同时运行同一脚本的两个实例的典型方法如下所示:
[ -f ".lock" ] && exit 1
touch .lock
# do something
rm .lock
有没有更好的方法从shell脚本锁定文件,避免竞争条件?必须使用目录吗?
解决方法:
是的,示例脚本确实存在竞争条件.你可以使用bash的noclobber选项,以便在比赛的情况下失败,当不同的脚本在-f测试和触摸之间潜入时.
以下是一个示例代码片段(灵感来自this article),它说明了该机制:
if (set -o noclobber; echo "$$" > "$lockfile") 2> /dev/null;
then
# This will cause the lock-file to be deleted in case of a
# premature exit.
trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT
# Critical Section: Here you'd place the code/commands you want
# to be protected (i.e., not run in multiple processes at once).
rm -f "$lockfile"
trap - INT TERM EXIT
else
echo "Failed to acquire lock-file: $lockfile."
echo "Held by process $(cat $lockfile)."
fi