in reply to File Locking

A couple of things:

1. Use flock() constants defined in Fcntl.pm.
use Fcntl ':flock'; ... flock $fh, LOCK_EX or exit $status; ...
2. You're redirecting STDOUT and STDERR and then using die(), which will clobber your TEST.NEW if flock() fails. Either don't use die() and just exit() or implement a logging mechanism of some sort so that you're not writing to STDOUT/STDERR.

3. If the file is locked, do you want to exit immediately or do you want the program to block and wait until it's unlocked?
# will block until file is unlocked flock $fh, LOCK_EX or exit $status; # will exit immediately if the file is locked flock $fh, LOCK_EX | LOCK_NB or exit $status;
--perlplexer

Replies are listed 'Best First'.
Re: Re: File Locking
by nimdokk (Vicar) on Apr 23, 2003 at 16:44 UTC
    How do I go about check to see if there is already a file lock? I want the program to exit if it cannot get a lock on the file.
      Do you have to delete the file from some other script? Or would it be more reasonable to simply truncate() TEST.NEW from your main script after it aquires the lock?
      open STDOUT, ">>$dir/TEST.NEW" or exit 1; open STDERR, ">>&STDOUT" or exit 2; flock STDOUT, LOCK_EX | LOCK_NB or exit 3; truncate STDOUT, 0; # delete everything from the file # The remainder of the program will be writing to an # empty file. close STDERR; close STDOUT;
      There is a way to check if the file is locked from another script but you can't safely delete it because as soon as you close the file, so that you can delete it, it will be unlocked and there is a slight chance that some other process will write to it in the interim.
      To prevent this from happening, both processes either need to use truncate(), in which case the file doesn't get deleted but you still accomplish the same thing - no data in the file; Or, as the second option, both processes need to use a second file that they would lock whenever they need to update/delete TEST.NEW.

      --perlplexer
        Actually, with this we should be able to safely delete the file because nothing else will be trying to access it or write to it except the program itself. If that makes sense.