当使用锁定文件来避免脚本的两个实例同时运行时,如何避免竞争状况? [英] How to avoid race condition when using a lock-file to avoid two instances of a script running simultaneously?
问题描述
避免同一脚本的两个实例同时运行的典型方法如下:
A typical approach to avoid two instances of the same script running simultaneously looks like this:
[ -f ".lock" ] && exit 1
touch .lock
# do something
rm .lock
是否有更好的方法来锁定shell脚本中的文件,从而避免出现竞争状况?必须使用目录吗?
Is there a better way to lock on files from a shell-script, avoiding a race condition? Must directories be used instead?
推荐答案
是的,示例脚本中确实存在竞争条件.您可以使用bash的noclobber
选项来在比赛中失败,而-f
测试和touch
之间会出现一个不同的脚本.
Yes, there is indeed a race condition in the sample script. You can use bash's noclobber
option in order to get a failure in case of a race, when a different script sneaks in between the -f
test and the touch
.
以下是示例代码段(受这篇文章的启发)说明了该机制:
The following is a sample code-snippet (inspired by this article) that illustrates the mechanism:
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
这篇关于当使用锁定文件来避免脚本的两个实例同时运行时,如何避免竞争状况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!