要锁定文件:
exec 3>filename # open a file handle; this part will always succeed
flock -x 3 # lock the file handle; this part will block
要释放锁:
exec 3>&- # close the file handle
您还可以按照集群手册页描述的方式进行操作:
{
flock -x 3
...other stuff here...
} 3>filename
...在这种情况下,当块退出时文件会自动关闭。 (这里也可以使用子shell,通过使用( )
而不是{ }
,但这应该是一个经过深思熟虑的决定——因为子 shell 会降低性能,并且会影响范围变量修改和其他状态更改)。
如果您运行的是足够新的 bash 版本,则无需手动管理文件描述符编号:
# this requires a very new bash -- 4.2 or so.
exec {lock_fd}>filename # open filename, store FD number in lock_fd
flock -x "$lock_fd" # pass that FD number to flock
exec {lock_fd}>&- # later: release the lock
...现在,对于您的函数,我们将需要关联数组和自动 FD 分配(并且,为了允许从不同路径锁定和解锁同一文件,GNU readlink)——所以这不适用于较旧的 bash 版本:
declare -A lock_fds=() # store FDs in an associative array
getLock() {
local file=$(readlink -f "$1") # declare locals; canonicalize name
local op=$2
case $op in
LOCK_UN)
[[ ${lock_fds[$file]} ]] || return # if not locked, do nothing
exec {lock_fds[$file]}>&- # close the FD, releasing the lock
unset lock_fds[$file] # ...and clear the map entry.
;;
LOCK_EX)
[[ ${lock_fds[$file]} ]] && return # if already locked, do nothing
local new_lock_fd # don't leak this variable
exec {new_lock_fd}>"$file" # open the file...
flock -x "$new_lock_fd" # ...lock the fd...
lock_fds[$file]=$new_lock_fd # ...and store the locked FD.
;;
esac
}
如果您使用的平台上 GNU readlink 不可用,我建议替换readlink -f
打电话给realpath
from sh-realpath 作者:Michael Kropat(仅依赖于广泛可用的 readlink 功能,而不是 GNU 扩展)。