From: "Benjamin J. Tilly" Date: 2001-06-22T04:35:00+09:00 Subject: [ruby-talk:16721] RE: File.flock blocks forever This is not an answer to your question, but it is a note about flock. It is important to flush all buffers before you unlock a flock, and in the common case where you are going to close it right after, it is both safest and simplest to just close the file. On close you are guaranteed to flush the buffer, and the OS guarantees that you drop the lock. Less code and does what you want..good argument in my books. But since so many people get this wrong, Perl guarantees a flush on a filehandle before you unlock. If Ruby doesn't do this, it would be a good idea. Incidentally if you will be editing a file you either have to open the file in read-write mode, or you need to flock a sentinel file instead. For BerkeleyDB you need to either use its locking routines or flock a sentinel file. There are serious race conditions with the naive "lock each operation with a file I am editing" or with flocking the filehandle to your dbm. Cheers, Ben >===== Original Message From Michael Witrant ===== >Hello, > >I try to use File.flock to lock a file in a cgi script, but I can't get >it to work in my test script. >It creates a file and write "foo". A thread that will write "bar" in 0.1 >secondes is started, and an infinite loop reads the file and print the >result. >The script displays some "foo" and waits, probably for the file to be >unlocked. No "bar". I expected some "foo", then many "bar". > >Here is the script: > >filename = "/tmp/flock-test" > >f = open(filename, "w") >f.puts "foo" >f.close > >Thread.new { > sleep .1 > f = open(filename, "w") > f.flock(File::LOCK_EX) > f.puts "bar" > f.flock(File::LOCK_UN) > f.close >} > >loop do > f = open(filename) > f.flock(File::LOCK_EX) > puts f.gets > f.flock(File::LOCK_UN) > f.close >end > >With the help of some puts, it seems to be blocking on f.gets in the >main thread and f.flock in the writing thread. >If I add "sleep .0001" in the main loop, it works. > >Where am I wrong? > >I tried to search "flock" on ruby-talk.com, but I got an Internal Server >Error. > > >Mike. >midulo.