| 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 | |||
| 27 | sub new | ||
| 28 | { | ||
| 29 | my ( $class, $file, $match, $self ) = splice @_, 0, 3; | ||
| 30 | |||
| 31 | $self->{file} = $file; | ||
| 32 | $self->{match} = $match; | ||
| 33 | |||
| 34 | my $mode = -f ( $file = File::Spec->rel2abs( $file ) ) ? '+<' : '+>'; | ||
| 35 | |||
| 36 | confess "invalid lock file: $file" if -e $file && ! -f $file; | ||
| 37 | confess "open $file: $!" unless open $self->{fh}, $mode, $file; | ||
| 38 | |||
| 39 | bless $self, ref $class || $class; | ||
| 40 | } | ||
| 41 | |||
| 42 | =head1 METHODS | ||
| 43 | |||
| 44 | =head3 check() | ||
| 45 | |||
| 46 | Returns PID of owner, undef if not locked. | ||
| 47 | |||
| 48 | =cut | ||
| 49 | sub check | ||
| 50 | { | ||
| 51 | my $self = shift; | ||
| 52 | my ( $file, $fh, $pid ) = $self->{file}; | ||
| 53 | return open( $fh, '<', $file ) && ( $pid = $self->read( $fh ) ) | ||
| 54 | ? $pid : undef; | ||
| 55 | } | ||
| 56 | |||
| 57 | =head3 lock() | ||
| 58 | |||
| 59 | Attempts to acquire lock. Returns pid if successful, undef otherwise. | ||
| 60 | |||
| 61 | =cut | ||
| 62 | sub lock | ||
| 63 | { | ||
| 64 | local $| = 1; | ||
| 65 | |||
| 66 | my ( $self, $pid ) = shift; | ||
| 67 | my $fh = $self->{fh}; | ||
| 68 | |||
| 69 | return $pid unless flock $fh, LOCK_EX | LOCK_NB; | ||
| 70 | |||
| 71 | unless ( $pid = $self->read() ) | ||
| 72 | { | ||
| 73 | seek $fh, 0, 0; | ||
| 74 | truncate $fh, 0; | ||
| 75 | print $fh ( $pid = $$ ); | ||
| 76 | } | ||
| 77 | elsif ( $pid ne $$ ) | ||
| 78 | { | ||
| 79 | $pid = undef; | ||
| 80 | } | ||
| 81 | |||
| 82 | flock $fh, LOCK_UN; | ||
| 83 | return $pid; | ||
| 84 | } | ||
| 85 | |||
| 86 | =head3 read() | ||
| 87 | |||
| 88 | Returns a running pid or undef. | ||
| 89 | |||
| 90 | =cut | ||
| 91 | sub read | ||
| 92 | { | ||
| 93 | my ( $self, $fh, $pid ) = splice @_, 0, 2; | ||
| 94 | $pid = seek( ( $fh ||= $self->{fh} ), 0, 0 ) && read( $fh, $pid, 16 ) | ||
| 95 | && $pid =~ /^(\d+)/ && kill( 0, $1 ) ? $1 : undef; | ||
| 96 | |||
| 97 | return $pid unless defined $pid && $self->{match}; | ||
| 98 | |||
| 99 | open my $ch, '<', "/proc/$pid/cmdline" or return undef; | ||
| 100 | my $cmdline = <$ch>; | ||
| 101 | |||
| 102 | return $cmdline =~ /$self->{match}/ ? $pid : undef; | ||
| 103 | } | ||
| 104 | |||
| 105 | 1; |