在文件中常见的锁争用情况? [英] race condition in the common lock on file?

查看:223
本文介绍了在文件中常见的锁争用情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是创建一个使用的文件系统锁定的标准方法。例如,visudo命令使用它:

  [-f.lock]&放大器;&安培; 1号出口
触摸.lock
# 做一点事
RM .lock

1)我很困惑,因为有一个竞争条件,但Linux的使用它

2)是否有更好的办法从壳锁定的文件?

3)或者我必须使用目录呢?

找到解决方案:男人锁文件


解决方案

是的,的确在示例脚本中的竞争条件。可以使用bash的noclobber选项,以获得一个故障在比赛中,当不同的脚本的测试和触摸之间钻进的情况

它这里描述。我摘录的关键部分,与一对夫妇的注释(prefixed由BK:):


  

一个可能的解决方案是使用IO重定向和bash的noclobber选项模式,这将不重定向到一个现有的文件。我们可以使用类似于:


 如果(设置-o noclobber选项;回声$$>中$锁定文件),2  - ;的/ dev / null的;
然后
   #BK:这将导致锁定文件在其他出口的情况下,被删除
   陷阱RM -f$锁文件;退出$? INT TERM EXIT   #临界区BK:(被保护位)   RM -f$锁定文件
   陷阱 - INT TERM EXIT
其他
   回声未能获取锁文件:$锁定文件
   回声由$召开(猫$文件锁)
科幻

this is the standard approach to create locks using file system. For example, visudo uses it:

[ -f ".lock" ] && exit 1
touch .lock
# do something
rm .lock

1) I'm confused, for there's a race condition, yet Linux uses it

2) is there a better way to lock on files from shell?

3) or do I have to use directories instead?

Found solution: man lockfile.

解决方案

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 test and the touch.

It's described here. I've excerpted the critical piece, with a couple of annotations (prefixed by BK:):

A possible solution to this is to use IO redirection and bash's noclobber mode, which won't redirect to an existing file. We can use something similar to:

if ( set -o noclobber; echo "$$" > "$lockfile") 2> /dev/null; 
then
   # BK: this will cause the lock file to be deleted in case of other exit
   trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT

   # critical-section BK: (the protected bit)

   rm -f "$lockfile"
   trap - INT TERM EXIT
else
   echo "Failed to acquire lockfile: $lockfile." 
   echo "Held by $(cat $lockfile)"
fi

这篇关于在文件中常见的锁争用情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆