本文简要介绍ruby语言中 File.flock 的用法。
用法
flock(locking_constant) → 0 or false
根据locking_constant(下表中值的逻辑or)锁定或解锁文件。如果指定了 File::LOCK_NB,则返回 false,否则操作将被阻止。并非在所有平台上都可用。
锁定常量(在类 File 中):
LOCK_EX | Exclusive lock. Only one process may hold an
| exclusive lock for a given file at a time.
----------+------------------------------------------------
LOCK_NB | Don't block when locking. May be combined
| with other lock options using logical or.
----------+------------------------------------------------
LOCK_SH | Shared lock. Multiple processes may each hold a
| shared lock for a given file at the same time.
----------+------------------------------------------------
LOCK_UN | Unlock.
例子:
# update a counter using write lock
# don't use "w" because it truncates the file before lock.
File.open("counter", File::RDWR|File::CREAT, 0644) {|f|
f.flock(File::LOCK_EX)
value = f.read.to_i + 1
f.rewind
f.write("#{value}\n")
f.flush
f.truncate(f.pos)
}
# read the counter using read lock
File.open("counter", "r") {|f|
f.flock(File::LOCK_SH)
p f.read
}
相关用法
- Ruby File.fnmatch用法及代码示例
- Ruby File.ftype用法及代码示例
- Ruby File.identical?用法及代码示例
- Ruby File.dirname用法及代码示例
- Ruby File.directory?用法及代码示例
- Ruby File.link用法及代码示例
- Ruby File.expand_path用法及代码示例
- Ruby File.lstat用法及代码示例
- Ruby File.umask用法及代码示例
- Ruby File.absolute_path?用法及代码示例
- Ruby File.rename用法及代码示例
- Ruby File.split用法及代码示例
- Ruby File.chmod用法及代码示例
- Ruby File.atime用法及代码示例
- Ruby File.to_path用法及代码示例
- Ruby File.stat用法及代码示例
- Ruby File.chown用法及代码示例
- Ruby File.path用法及代码示例
- Ruby File.absolute_path用法及代码示例
- Ruby File.mtime用法及代码示例
- Ruby File.build用法及代码示例
- Ruby File.join用法及代码示例
- Ruby File.readlink用法及代码示例
- Ruby File.new用法及代码示例
- Ruby File.world_writable?用法及代码示例
注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 File.flock。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
