I am trying to check a piece of code ( $code), which should ensure that only one instance of the program starts at a time:
use strict;
use warnings;
( my $code = <<'CODE') =~ s/^\s+//gm;
use strict;
use warnings;
use Fcntl qw(:flock);
open our $Lock, '<', $0 or die "Can't lock myself $0: $!";
flock $Lock, LOCK_EX | LOCK_NB
or die "Another instance of $0 is already running. Exiting ...\n";
sleep(2);
CODE
my $progfile = '/tmp/x';
open my $fh, '>', $progfile or die $!;
print $fh $code;
close $fh;
$|++;
my $ex1 = system("perl $progfile &");
print "First system(): $ex1\n";
my $ex2 = system("perl $progfile");
print "Second system(): $ex2\n";
I was expecting the second call to system()return a non-zero value ( $ex2), since it cannot get the lock and dies. However, I get:
$ perl test_lock
First system(): 0
Another instance of /tmp/x is already running. Exiting ...
Second system(): 0
What is wrong with my assumption? (Is there a better way to check $code?)
source
share