Search This Blog

Sunday 23 November 2014

Running One Instance of a Process (Perl implementations)

1) Locking through PID file


use strict;
use warnings;
use utf8;
use v5.10;
use Carp;

# prevent sending of the 'stop' signal to this process,
# if the terminal, from which the script is run, is disconnected
$SIG{HUP} = 'IGNORE';
 
my $lock_file = "$0.lock"; 
 
exit 0 if -e $lock_file;

open my $fhl, '>', $lock_file or die "Cannot proceed: $!";
close $fhl;

# Remove the lock file if the process ended abnormally
for my $signal (qw(INT KILL TERM __DIE__)) {
    $SIG{$signal} = \&sig_handler;
}

while (1) { 
    sleep 13; 
    unlink $lock_file or croak "Cannot delete $lock_file: $!" if -e $lock_file; 
    exit (0);
}

# ------------------- SUBROUTINES ----------------------

sub sig_handler {
    say "\t>>> deleting $lock_file";
    unlink $lock_file or croak "Cannot delete $lock_file: $!";
}

2) Locking the process

a) 
use strict;
use warnings;
use utf8;
use Carp;
use Fcntl ':flock'; 

BEGIN { 
open my $process, '<', $0 or die "Cannot start process $0: $!" ;
    flock $process, LOCK_EX|LOCK_NB or croak "Cannot lock $0, already running  - $!";
} 

while (1) {}

b)

use strict;
use warnings;
use utf8;
use Fcntl ':flock';

BEGIN {
    open  *{0}  or die "Cannot start process $0: $!";
    flock *{0}, LOCK_EX|LOCK_NB or die "Cannot lock $0, already running - $!";
}
 
while (1) {}

c)

use strict;
use warnings;
use utf8;
use Fcntl ':flock';
 
flock DATA, LOCK_EX|LOCK_NB or die "Cannot lock $0- $!";
 
while (1) {}
 
__DATA__

No comments: