From: Robert Klemme Date: 2007-04-30T18:25:14+09:00 Subject: Re: Editing a text file On 28.04.2007 20:44, barjunk wrote: > >> I consider Ara the definitive source especially when it comes to >> flock'ing NFS mounted files, see for example: >> >> http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/97211 >> >> For the low profile solution check out >> >> http://ruby-doc.org/core/classes/File.html#M002576 >> >> Kind regards >> >> robert > > Thanks Robert. > > So if I'm editing this file, the basic idea here is to do this: > > require 'lockfile' > > Lockfile('lock', :retries => 0) do > # edit my file here > end > > And that's it? I'm assuming this will also work on a non-NFS file > system as well. That will do just fine. No, I meant: the basic mechanism uses io.flock, e.g. 11:22:07 [Temp]: cat fl.rb #!/usr/bin/ruby id=ARGV.shift || $$ File.open("x", "a") do |io| puts "#{id}: Start #{Time.now}" io.flock(File::LOCK_EX) io.puts "#{id}: #{Time.now.inspect}" sleep 2 io.puts "#{id}: #{Time.now.inspect}" puts "#{id}: End #{Time.now}" end 11:22:12 [Temp]: rm x; for ((i=0;i<10;++i)) do echo $i; ./fl.rb $i & done; sleep 30 removed `x' 0 [1] 272 1 [2] 2240 2 [3] 3568 3 [4] 2644 4 0: Start Mon Apr 30 11:22:20 +0200 2007 [5] 2688 5 2: Start Mon Apr 30 11:22:20 +0200 2007 1: Start Mon Apr 30 11:22:20 +0200 2007 [6] 2020 6 [7] 3472 7 3: Start Mon Apr 30 11:22:20 +0200 2007 [8] 3332 8 4: Start Mon Apr 30 11:22:20 +0200 2007 [9] 3788 9 [10] 3456 5: Start Mon Apr 30 11:22:20 +0200 2007 6: Start Mon Apr 30 11:22:21 +0200 2007 7: Start Mon Apr 30 11:22:21 +0200 2007 8: Start Mon Apr 30 11:22:21 +0200 2007 9: Start Mon Apr 30 11:22:21 +0200 2007 0: End Mon Apr 30 11:22:22 +0200 2007 2: End Mon Apr 30 11:22:24 +0200 2007 1: End Mon Apr 30 11:22:26 +0200 2007 3: End Mon Apr 30 11:22:28 +0200 2007 4: End Mon Apr 30 11:22:30 +0200 2007 5: End Mon Apr 30 11:22:32 +0200 2007 6: End Mon Apr 30 11:22:34 +0200 2007 7: End Mon Apr 30 11:22:36 +0200 2007 8: End Mon Apr 30 11:22:38 +0200 2007 9: End Mon Apr 30 11:22:40 +0200 2007 [1] Done ./fl.rb $i [2] Done ./fl.rb $i [3] Done ./fl.rb $i [4] Done ./fl.rb $i [5] Done ./fl.rb $i [6] Done ./fl.rb $i [7] Done ./fl.rb $i [8] Done ./fl.rb $i [9]- Done ./fl.rb $i [10]+ Done ./fl.rb $i 11:22:51 [Temp]: From the timings you can nicely see that exclusive locking works. robert