本文簡要介紹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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。