I found an article on this at
The Perl Journal. Here's my second version:
#!/usr/bin/perl
use strict;
use warnings;
use Sem;
use Storable qw/lock_store lock_retrieve/;
use CGI;
my $q = new CGI;
my $sem = Sem->new('semaphore.txt');
my $x = lock_retrieve('k.dat') or die "Can't open k.dat: $!";
$x->{counter}++;
lock_store($x, 'k.dat') or die "Can't save k.dat: $!";
$sem->unlock;
print $q->header;
And here's the Sem.pm code:
package Sem;
sub new {
my $class = shift(@_);
use Carp ();
my $filespec = shift(@_) || Carp::croak("What filespec?");
open my $fh, ">", $filespec or Carp::croak("Can't open semaphore f
+ile $filespec: $!");
chmod 0666, $filespec; # assuming you want it a+rw
use Fcntl 'LOCK_EX';
flock $fh, LOCK_EX;
return bless {'fh' => $fh}, ref($class) || $class;
}
sub unlock {
close(delete $_[0]{'fh'} or return 0);
return 1;
}
1;
Is there anyway to test this? Should I use the apache benchmark tool to send a bunch of concurrent requests to the cgi?