in reply to Order of flock and open
One issue is if you're opening a file for something other than reading. If you open a file for append, you should seek() to the end of the file after you acquire the lock, to make sure no one else appended to the file after you opened it.
If you're opening a file for destructive write, you have a bigger problem. Opening destroys the file, but you can't lock the file until you open it. One solution to this is to lock a different file, as someone else described. Another solution is to open the file twice: open it once for reading, lock it, and then open it for writing once you know you have the lock. As long as you keep the first filehandle open, you'll keep the lock.open my $FH, ">>foo" or die "can't open"; flock $FH, LOCK_EX or die "no lock"; seek ($FH, 0, 2);
Finally, is the situation you describe, where you want to lock a file, rebuild it in a temporary file, and then copy the tempfile over the real file. The issue here is, with most filesystems, when you use rename() or `mv` to replace the real file with the newly built tempfile, you lose your lock on the file. If this is okay (you're done with the file when you copy it over) then it's probably not a problem. But if you wanted to perform any other operations on the file while it's still locked, you probably need to use the "lock a different file" technique.open my $LOCK, "<foo" or die "can't open for locking"; flock $LOCK, LOCK_EX or die "Can't lock"; open my $FH, ">foo" or die "can't open for writing"; print $FH "I own this file\n"; close $FH; close $LOCK;
Alan
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
•Re: Re: Order of flock and open
by merlyn (Sage) on Apr 30, 2003 at 20:08 UTC | |
by ferrency (Deacon) on Apr 30, 2003 at 20:20 UTC |