Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

File#flock

(::int locking_constant) -> (0 | false)
flock(locking_constant) → 0 or false

Locks or unlocks file self according to the given locking_constant, a bitwise OR of the values in the table below.

Not available on all platforms.

Returns false if File::LOCK_NB is specified and the operation would have blocked; otherwise returns 0.

Constant Lock Effect
File::LOCK_EX Exclusive Only one process may hold an exclusive lock for self at a time.
File::LOCK_NB Non-blocking No blocking; may be combined with File::LOCK_SH or File::LOCK_EX using the bitwise OR operator |.
File::LOCK_SH Shared Multiple processes may each hold a shared lock for self at the same time.
File::LOCK_UN Unlock Remove an existing lock held by this process.

Example:

Example
# Update a counter using an exclusive lock.
# Don't use File::WRONLY because it truncates the file.
File.open('counter', File::RDWR | File::CREAT, 0644) do |f|
  f.flock(File::LOCK_EX)
  value = f.read.to_i + 1
  f.rewind
  f.write("#{value}\n")
  f.flush
  f.truncate(f.pos)
end

# Read the counter using a shared lock.
File.open('counter', 'r') do |f|
  f.flock(File::LOCK_SH)
  f.read
end
See also #ctime #lstat #chown #mtime also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0