From: Brian Candler Date: 2003-07-26T23:57:47+09:00 Subject: Re: Confused about locking a file via file.flock(File::LOCK_EX) On Sat, Jul 26, 2003 at 08:57:00PM +0900, Ludwigi Beethoven wrote: > I guess I would have to grab the file and update it > rather quickly, and hope that nobody else is updating > it at the same time via some other way. The requirement was to prevent another user editing the same file with 'vi', right? On my system (FreeBSD), if I edit a file with vi, then try to edit the same file in vi in another window, I get: /etc/motd already locked, session is read-only. /etc/motd: unmodified, readonly: line 1 This implies that there is some sort of locking going on. Now, if I run this test program: def testlock(filename) f = File.open(filename) f.flock(File::LOCK_EX) sleep 30 f.close end testlock("/etc/motd") then vi /etc/motd also reports that the file is locked. Is that not the case for you? If not, then the "update it rather quickly and hope" is most safely done by: - creating a copy of the file with a different name and modified contents - doing a 'rename' operation to replace the original file with it This is an atomic operation - it will either succeed or fail. Of course someone else who has it open in a buffer could overwrite it again, but at least it will always be a complete and valid file, not corrupted by two people writing to it simultaneously. Regards, Brian.