O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.13. Locking a File

Problem

You want to prevent other threads or processes from modifying a file that you're working on.

Solution

Open the file, then lock it with File#flock. There are two kinds of lock; pass in the File constant for the kind you want.

  • File::LOCK_EX gives you an exclusive lock, or write lock. If your thread has an exclusive lock on a file, no other thread or process can get a lock on that file. Use this when you want to write to a file without anyone else being able to write to it.

  • File::LOCK_SH will give you a shared lock, or read lock. Other threads and processes can get their own shared locks on the file, but no one can get an exclusive lock. Use this when you want to read a file and know that it won't change while you're reading it.

Once you're done using the file, you need to unlock it. Call File#flock again, and pass in File::LOCK_UN as the lock type. You can skip this step if you're running on Windows.

The best way to handle all this is to enclose the locking and unlocking in a method that takes a block, the way open does:

	  def flock(file, mode)
	    success = file.flock(mode)
	    if success
	      begin
	        yield file
	      ensure
	        file.flock(File::LOCK_UN)
	    end
	  end
	  return success
	end

This makes it possible to lock a file without having to worry about unlocking it later. Even if your block raises an exception, the file will be unlocked and another thread can use it.

	open('output', 'w') do |f|
	  flock(f, File::LOCK_EX) do |f|
	  f << "Kiss me, I've got a write lock on a file!"
	  end
	end

Discussion ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required