Jeremy Kister > File-TinyLock > File::TinyLock



Annotate this POD

View/Report Bugs
Module Version: 1.20   Source  


File::TinyLock - Utility for process locking and unlocking.


  use File::TinyLock;

  my $LOCK = '/tmp/testing.lock';

  my $locksmith = File::TinyLock->new(lock => $LOCK);
  if( $locksmith->lock() ){
    warn "we have locked\n";
    warn "we have unlocked\n";
    warn "could not lock..\n";


File::TinyLock provides lock, unlock, and checklock methods for working with process locking. This utility attempts to be useful when you require one of a process to be running at a time, but someone could possibly try to spawn off a second (such as having a crontab where you are *hoping* one job ends before the next starts).


lock( [LOCK] [,OPTIONS] );

LOCK is a mandatory lock file.

OPTIONS are passed in a hash like fashion, using key and value pairs. Possible options are:

mylock - Unique file to identify our process (Default: auto-generated) - *must* be on the same filesystem as <LOCK>

retries - Number of times to retry getting a lock (Default: 5)

retrydelay - Number of seconds to wait between retries (Default: 60)

debug - Print debugging info to STDERR (0=Off, 1=On) (Default: 0).


Here are a list of return codes of the lock function and what they mean:

0 The process could not get a lock.
1 The process has obtained a lock.

.. and for the checklock function:

0 The process does not have a lock.
1 The process has a lock.

.. and the unlock function:

Note: method will die if we cannot modify <LOCK>


  # run the below code twice ( e.g. perl ./ & ; perl ./ )

  use strict;
  use File::TinyLock;

  my $lock = '/tmp/testing.lock';
  my $locksmith = File::TinyLock->new(lock => $lock, debug => 1);

  my $result = $locksmith->lock();
    print "We have obtained a lock\n";
        # do stuff 

  sleep 30;



If you leave lock files around (from not unlocking the file before your code exits), File::TinyLock will try its best to clean up and/or determine if the lock files are stale or not. This is best effort, and may yield false positives. For example, if your code was running as pid 1234 and crashed without unlocking, stale detection may fail if there is a new process running with pid 1234.


Locking will only remain successfull while your code is active. You can not lock, let your code exit, and start your code again - doing so will result in stale lock files left behind.

start code -> get lock -> do stuff -> unlock -> exit;


<a href="">Jeremy Kister</a>

syntax highlighting: