-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPlock.pm
127 lines (92 loc) · 2.31 KB
/
Plock.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package JoeDog::Plock;
use IO::Socket;
use vars qw($VERSION);
$VERSION = '1.0.1';
my $portlock = undef;
my $debug = 0;
use constant DEFAULT_PORT => 26400;
$| = 1;
=head1 SYNOPSIS
JoeDog::Plock - A perl extension to ensure just one copy of a running application.
Plock stands for Port LOCK. This method is particularly useful if
your application runs on an NFS volume.
use JoeDog::Plock;
my $lock = new JoeDog::Plock(55555);
if (! $lock->lock()) {
print "A copy of $0 is already running....\n";
exit(1);
}
# put your script here....
$lock->unlock();
exit;
=head1 METHODS
=item B<new>
$lock = new JoeDog::Plock([optional_number]);
JoeDog::Plock constructor; returns a reference to a JoeDog::Plock object.
If this constructor is called with no parameters, it uses the default port (26400).
You can override that port number with an optional number. We suggest you pick ports
between 10000 and 60000.
=cut
sub new {
my $type = shift;
my $self = {};
$self->{'port'} = $_[0];
$self->{'debug'} = 0;
$self->{'port'} = (int($self->{'port'}) <= 0) ? DEFAULT_PORT : $self->{'port'};
bless $self, $type;
}
=item B<lock>
$lock->lock()
This is our test to see if a copy of our script is already running. Consider this
example:
if (! $lock->lock()) {
print "A copy of $0 is already running.\n";
exit(1);
}
=cut
sub lock() {
my $this = shift;
my $port = $this->{'port'};
$portlock = new IO::Socket::INET (
LocalHost => 'localhost',
LocalPort => $port,
Proto => 'tcp',
Listen => 1
);
$this->debug("lock() :: port ($port) ok");
unless($portlock) {
return 0;
}
return 1;
}
=item B<lock>
$lock->unlock()
Remove the Port LOCK by closing the socket.
=cut
sub unlock() {
my $this = shift;
if (defined($portlock)) {
close($portlock);
}
$portlock= undef;
$this->debug("unlock() :: ok");
}
sub debug() {
my $this = shift;
my (@parm) = (@_);
my $msg = join(' : ',@parm);
my $scr = "Ver$VERSION";
if ($this->{'debug'} > 0) {
print "$scr - $msg\n";
}
}
=item B<set_debug()>
$conf->set_debug();
This options turns on debugging. It tells JoeDog::Plock to print what it reads to STDOUT;
=cut
sub set_debug(){
my $this = shift;
$this->{"debug"} = 1;
return;
}
1;