I've had a few problems lately with file locking. Admittedly my first solution where I was having the problems was shoddy, to say the least.
Let's say I have a system where more than one process will try to grab a pair of files (two associated files), read it/them, copy it/them elsewhere, and delete the originals. I want only one copy of the originals to be floating around. The initial solution was
get handles,
lock,
copy,
unlock,
unlink.
My processes were both able to get file handles, then if the first released its lock before the second tried to get one, comedy ensued. s/comedy/trouble/.
I thought I might have fixed that by unlinking before releasing the locks (might work?), but I was still getting some duplicates, because a filehandle still points to the file data even if it's been unlinked, and that handle can still get a lock on the filehandle (naivety made me think this might work, I suppose).
The newest fix, which seems to be working (touch wood) only because the file is actually two files, is to get a lock on one, then get a filehandle to the other, and then get a lock on it. If any of these fails, then give up. I think this is only working because one of the two files is essentially behaving like a lock file for the other.
My question is really this: is there a way to do this with only one file, not using a lock file?
I read the file locking tutorial
7058 (and the associated replies) by
turnstep, but it still leaves some threads hanging. Also, I suppose this isn't really a perl question, but I'm guessing there might be some people out there who have done similar...