in reply to File Locking Problem

So don't clobber it first. See open for the scoop on the +< mode.

open HANDLE, "<", $file or die "Can't open $file for reading: $!"; flock HANDLE, LOCK_SH or die "Can't get a shared lock to $file: $!"; # Open the file without clobbering it. open WRITER, "+<", $file or die "Can't open $file for writing: $!"; flock WRITER, LOCK_EX or die "Can't get an exclusive lock to $file: $! +"; truncate WRITER, 0 or die "Can't truncate $file: $!";

Replies are listed 'Best First'.
Re^2: File Locking Problem
by Anonymous Monk on Jul 28, 2004 at 21:07 UTC
    Just be careful not to assume that $file exists, because if it doesn't you won't be able to open it with +<. You may want to do something like:
    if (-e "$file") { open WRITER, "+<$file", $file or die "Can't open: $!"; flock WRITER, LOCK_EX or die "Can't lock $file: $!"; truncate WRITER, 0 or die "Can't truncate $file: $!"; } else { open WRITER, ">$file" or die "Can't open: $!"; flock(WRITER, LOCK_EX or die "Can't lock $file: $!"; } #do whatever....
      How does the overwriting open prevent stepping on a file if the file is created after the -e test and before the overwrite?
        It doesn't, but you will at least be able to open a filehandle (you just have to hope that the interval between the two is small enough that you won't run into problems). It's not an ideal solution, certainly, but is there a way to open a read/write handle on a file without clobbering it if it does exist and that won't fail if the file doesn't exist?
Re^2: File Locking Problem
by Anonymous Monk on Jul 28, 2004 at 20:10 UTC
    *thwack*

    Good call. Should have seen that one. =)