blib/lib/MYDan/Util/ProcLock.pm untested

filter: Statementstmt 0.0% 0 / 47 Branchbran 0.0% 0 / 22 Conditioncond 0.0% 0 / 26 MC/DCmcdc 0.0% 0 / 15 Subroutinesub 0.0% 0 / 10 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 124 CC 12 SCAR 27.7
CC
12
Cov
0%
new
30.0
lock
20.0
read
20.0
CRAP 15.9
1 package MYDan::Util::ProcLock;
2  
3 =head1 NAME
4  
5 MYDan::Util::ProcLock - Advisory lock using a regular file
6  
7 =head1 SYNOPSIS
8  
9 use MYDan::Util::ProcLock;
10  
11 my $lock = MYDan::Util::ProcLock->new( '/lock/file' );
12  
13 if ( my $pid = $lock->check() )
14 {
15 print "Locked by $pid.\n";
16 }
17  
18 $lock->lock();
19
20 =cut
21 use strict;
22 use warnings;
23 use Carp;
24 use File::Spec;
25 use Fcntl qw( :flock );
26 use Digest::MD5;
27  
28 sub new
29 {
30 my ( $class, $file, $match, $self ) = splice @_, 0, 2;
31  
32 die "file undef" unless $self->{file} = $file;
33  
34 $ENV{mydan_proclock_md5} = $self->{match} = Digest::MD5->new()->add( $file )->hexdigest();;
35  
36 my $mode = -f ( $file = File::Spec->rel2abs( $file ) ) ? '+<' : '+>';
37  
38 confess "invalid lock file: $file" if -e $file && ! -f $file;
39 confess "open $file: $!" unless open $self->{fh}, $mode, $file;
40  
41 bless $self, ref $class || $class;
42 }
43  
44 =head1 METHODS
45  
46 =head3 check()
47  
48 Returns PID of owner, undef if not locked.
49  
50 =cut
51 sub check
52 {
53 my $self = shift;
54 my ( $file, $fh, $pid ) = $self->{file};
55 return open( $fh, '<', $file ) && ( $pid = $self->read( $fh ) )
56 ? $pid : undef;
57 }
58  
59 =head3 lock()
60  
61 Attempts to acquire lock. Returns pid if successful, undef otherwise.
62  
63 =cut
64 sub lock
65 {
66 local $| = 1;
67  
68 my ( $self, $pid ) = shift;
69 my $fh = $self->{fh};
70  
71 return $pid unless flock $fh, LOCK_EX | LOCK_NB;
72  
73 unless ( $pid = $self->read() )
74 {
75 seek $fh, 0, 0;
76 truncate $fh, 0;
77 print $fh ( $pid = $$ );
78 }
79 elsif ( $pid ne $$ )
80 {
81 $pid = undef;
82 }
83
84 flock $fh, LOCK_UN;
85 return $pid;
86 }
87  
88 =head3 read()
89  
90 Returns a running pid or undef.
91  
92 =cut
93 sub read
94 {
95 my ( $self, $fh, $pid ) = splice @_, 0, 2;
96 $pid = seek( ( $fh ||= $self->{fh} ), 0, 0 ) && read( $fh, $pid, 16 )
97 && $pid =~ /^(\d+)/ && kill( 0, $1 ) ? $1 : undef;
98
99 return $pid unless defined $pid && $self->{match};
100  
101 open my $ch, '<', "/proc/$pid/environ" or return undef;
102 my $cmdline = <$ch>;
103 close $ch;
104  
105 return $cmdline =~ /$self->{match}/ ? $pid : undef;
106 }
107
108 1;