当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Ruby File.flock用法及代码示例


本文简要介绍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-lang.org大神的英文原创作品 File.flock。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。