------------------------------------------------
On Wed, 29 Jan 2003 13:42:49 +0100, "Enric Roca" <[EMAIL PROTECTED]> wrote:

> Hello,
> 
> I'm new in Perl programming and I think that this is an easy question for
> you:
> 
> I'm using Apache 1.3.26 and Perl 5.5.3 and I don't want to install
> additional modules if I can avoid it.
> I have an script, ex. test.pl that must control if it is already executing,
> and if it is, it must wait for some seconds. I don't want to use
> Proc::ProcessTable or other libraries. I would like to do this with the
> standard Perl 5.5.3.
> 
> So, I need to create a global variable (environment variable, etc) and set
> his value to EXECUTING (1 for instance) when the script begins and change
> his value to FREE (0 for example) when the perl script finish. Every time
> that the script begins must check the value of this variable and wait some
> seconds and try again if the other processes have finished.
> 
> Is there any easy way to do this without installing extra modules ?
> 

This is generally handled with a lock file.  At the start of the script open a file 
for writing, write something to it if you want (usually the PID) and then close it, do 
your work, and then remove the file.  The script should check to see if the file 
exists before creating it, therefore you know if there is already one processing.  
Don't forget to catch your exceptions lest, the lock file may exist and the process 
may not be running....

 
use Fcntl ':flock';         # import LOCK_* constants

# create the lock file
my $LOCK;
open $LOCK, ">.lock" or die "Unable to initialize, couldn't create lock file\n";
my $flock = flock($LOCK, (LOCK_EX|LOCK_NB));
unless ($flock) {
   die "Unable to initialize, couldn't lock the lock file, LOCK EXISTS!\n";
}
autoflush $LOCK 1;
print $LOCK $$;
close $LOCK or die "Unable to initialize, couldn't close lock file handle, LOCK 
EXISTS!\n";

then somewhere before this you want to do something similar to:

if (-e '.lock') {
    print "$0 already executing...quitting.";
    exit(1);
}

-- UNTESTED --

http://danconia.org


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to