From: "Ara.T.Howard" Date: 2003-10-07T08:03:08+09:00 Subject: Re: bug in open/flock ? On Tue, 7 Oct 2003, Hal Fulton wrote: > Ara.T.Howard wrote: > > in the code below, i am able to obtain TWO exclusive locks on files using the > > following logic: > > > > iff flock(LOCK_EX | LOCK_NB) fails, then open again and retry > > > > this should not be possible should it?? > > > > note that the following code SHOULD deadlock - but does not. > > [snip] > > Aren't locks on a per-process basis? no.knotice that this will produce monotonically increasing timestamps: ~/eg/ruby > cat ./flock.rb #!/usr/local/ruby-1.8.0/bin/ruby require 'ftools' require 'tempfile' def compete who, f 5.times do |i| f.flock File::LOCK_EX f.puts format("%s:%d @ %f\n",who, i, Time.now.to_f) f.flock File::LOCK_UN end end path = format(__FILE__ + '.out') fd = open(path, File::WRONLY | File::TRUNC | File::CREAT) if fork compete 'PARENT', fd Process.wait rescue nil open(path){|f| puts f.read} fd.close File.rm_f path if File.exist? path else compete 'CHILD', fd end ~/eg/ruby > ./flock.rb PARENT:0 @ 1065472160.300986 PARENT:1 @ 1065472160.301536 CHILD:0 @ 1065472160.301911 CHILD:1 @ 1065472160.302190 CHILD:2 @ 1065472160.302303 CHILD:3 @ 1065472160.302411 CHILD:4 @ 1065472160.302520 PARENT:2 @ 1065472160.303144 PARENT:3 @ 1065472160.305026 PARENT:4 @ 1065472160.305172 flocks are durable across processes. i think they are held in the kernel open file table. on my systems, they even work on nfs between machines! (this is not normal) > Ruby threads all run in the same process. which is an even stronger argument for why no two threads (let alone processes) should EVER be able to obtain an exclusive lock at the same time. -a ==================================== | Ara Howard | NOAA Forecast Systems Laboratory | Information and Technology Services | Data Systems Group | R/FST 325 Broadway | Boulder, CO 80305-3328 | Email: ara.t.howard@noaa.gov | Phone: 303-497-7238 | Fax: 303-497-7259 | The difference between art and science is that science is what we understand | well enough to explain to a computer. Art is everything else. | -- Donald Knuth, "Discover" | ~ > /bin/sh -c 'for lang in ruby perl; do $lang -e "print \"\x3a\x2d\x29\x0a\""; done' ====================================