Ruby File.open with EXCL
Create a new file only if its name is still available.
A simple example
File.open with EXCL
- Start with An unused name a.txt
- Do this Create exclusively twice
- Result First succeeds, second fails
Syntax
File.open(name, exclusive_flags)
Run these examples in Ruby
Save one example at a time as lesson.rb. Use Ruby 2.6 or later.
ruby lesson.rbStop two desks claiming the same ticket
Two desks request the same claim number. Use exclusive creation for the second reservation so it cannot replace the first ticket, then report the collision to the clerk.
require 'tmpdir'
Dir.mktmpdir do |folder|
Dir.chdir(folder) do
flags = File::WRONLY | File::CREAT | File::EXCL
File.open("claim", flags) { |f| f.write("issued") }
begin
File.open("claim", flags) { }
rescue Errno::EEXIST
puts "already issued"
end
end
end
already issued
The second reservation identifies the existing name without overwriting its contents.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Two desks try to reserve the same filename using exclusive creation. What happens to the first successful reservation when the second desk tries?
Prepare a studio handover
A stage manager saves a two-word instruction for the next shift. Two desks try to reserve the same filename using exclusive creation. What happens to the first successful reservation when the second desk tries?
What to watch for
Checking for existence before creation opens a race. Use an atomic create-if-absent operation.