I\'d like to read and write a file atomically in Ruby between multiple independent Ruby processes (not threads).
Take a look at transaction
and open_and_lock_file
methods in "pstore.rb" (Ruby stdlib).
YAML::Store
works fine for me. So when I need to read/write atomically I (ab)use it to store data as a Hash
.
You want to use File#flock in exclusive mode. Here's a little demo. Run this in two different terminal windows.
filename = 'test.txt'
File.open(filename, File::RDWR) do |file|
file.flock(File::LOCK_EX)
puts "content: #{file.read}"
puts 'doing some heavy-lifting now'
sleep(10)
end