A short while ago Bart Lateur was kind enough to help me improve the method I
use for locking files. The routine he sent me is below (I have commented it
heavily to help me follow it, and used my own error reporting routine):

__SNIP__
use Fcntl;

my @lockfiles;
my $timeOut = 10;
END {
         for ( @lock_files ) { unlink }
}
sub lockFile    {
        #       Create a lock file for the file passed as a parameter.
        #       If no parameter is passed, return a false value.
        my $lock_file = shift() . '.lock';
        my $idle = time;
        local *LOCK;
        #       Now try and create a lock file. Try every 1/10th of a second if a file
already exists 
        until ( sysopen LOCK, $lock_file, O_CREAT|O_TRUNC|O_EXCL|O_WRONLY ) {
                #       Die if the file cannot be created within a specified time
                &outputError( 'Could not create a lock file within the time limit', 
$!) if
time - $idle > $timeOut;
                #       sleep for 1/10th of a second
                select undef, undef, undef, 0.1;
        }
        #       If we get here, then the lock file has been created successfully.
        #       Add the lockfile name to the list to be deleted.
        push @lock_files, $lock_file;
        #       Now send some data to the lock file (anything will do).
        print LOCK $$;
        close LOCK;
        
        return 1;
}
__END_SNIP__

I have just implemented this routine, and it works very well. Many thanks to
Bart. However, I am a little unsure about what to do if the script cannot
create a lock file within the prescribed time (in this case 10 seconds). I do
not want visitors to be faced with a dead script if a lock file is left on the
server for any reason. If possible, can anyone advise me of any method that I
can safely use to remove this file?

Any help would be much appreciated.

TIA,

Richard


__________________________________________________
Do You Yahoo!?
Everything you'll ever need on one web page
from News and Sport to Email and Music Charts
http://uk.my.yahoo.com

Reply via email to