in reply to Re: File Locking Problem
in thread File Locking Problem

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....

Replies are listed 'Best First'.
Re^3: File Locking Problem
by diotalevi (Canon) on Jul 28, 2004 at 21:26 UTC
    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?
        Perhaps you could try touching the file and then opening the read/write handle. If the file isn't there, touch will create it. If the file is there, touch won't hurt it (unless the timestamp is of importance to you, but if you're about to write to it you're going to change that anyway). The only danger is that the file might be deleted in between the touch and the open, but that should be a relatively short danger zone (and it will make the code a bit simpler).