Search code examples
rubyio

Why flock() works differently when the File object is new?


Here is the code and it works:

f = File.new('test', File::CREAT | File::RDWR)
f.flock(File::LOCK_EX)
f.flock(File::LOCK_EX)
puts 'Works!'

However, this one doesn't work:

File.new('test', File::CREAT | File::RDWR).flock(File::LOCK_EX)
File.new('test', File::CREAT | File::RDWR).flock(File::LOCK_EX)
puts 'Works!'

Can you explain why is that? My actual question is how to make the second snippet work?


Solution

  • how to make the second snippet work?

    Unlock the file with LOCK_UN before attempting relocking with LOCK_EX. Or don't use LOCK_EX.

    As to why this happens, see the documentation on flock(2).

    If a process uses open(2) (or similar) to obtain more than one file descriptor for the same file, these file descriptors are treated independently by flock(). An attempt to lock the file using one of these file descriptors may be denied by a lock that the calling process has already placed via another file descriptor.