flock用法详解 linux_Linux flock,如何“只是”锁定文件?

要锁定文件:

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手册页描述的方式执行此操作:

{

flock -x 3

...other stuff here...

} 3>filename

…在这种情况下,当块退出时文件会自动关闭. (子shell也可以在这里使用,通过using()而不是{},但这应该是一个慎重的决定 – 因为子shell有性能损失,范围变量修改和其他状态更改自己).

如果您运行的是足够新版本的bash,则无需手动管理文件描述符编号:

# this requires a very new bash -- 4.2 or so.

exec {lock_fd}>filename

flock -x "$lock_fd"

exec $lock_fd>&-

…现在,对于你的函数,我们将需要关联数组和自动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不可用的平台上,我建议用sh-realpath by Michael Kropat的realpath替换readlink -f调用(仅依赖于广泛使用的readlink功能,而不是GNU扩展).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值