blib/lib/IPC/Pidfile.pm untested

filter: Statementstmt 0.0% 0 / 43 Branchbran 0.0% 0 / 16 Conditioncond 0.0% 0 / 9 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 9 Podpod 0.0% 0 / 7 totaltotal 0.0% 0 / 84 SCAR 45.0
CC
9
Cov
0%
pidfile_lock
12.0
pidfile_is_fresh
12.0
pidfile_read
12.0
CRAP 90.0
1 use strict;
2 use warnings;
3 package IPC::Pidfile;
4 $IPC::Pidfile::VERSION = '0.01';
5 # ABSTRACT: run only instance of a program at a time
6 our $DEBUG = $ENV{IPC_PIDFILE_DEBUG};
7 our $PID = pid();
8  
9 # signal handler
10 $SIG{TERM} = $SIG{INT} = sub { exit(0) };
11  
12 pidfile_lock();
13  
14 END { pidfile_clear() }
15  
16  
17 sub pidfile_name { "$0.pid" }
18  
19 sub pidfile_lock
20 {
21 print "$PID pidfile_lock\n" if $DEBUG;
22 die "$0 is already running\n" if (-e pidfile_name()) && pidfile_is_fresh();
23 open my $pidfile, '>', pidfile_name() or die 'Unable to open pidfile ' . pidfile_name();
24 select((select($pidfile), $| = 1)[0]);
25 print $pidfile pid();
26 close $pidfile;
27 return 1;
28 }
29  
30 sub pidfile_is_fresh
31 {
32 print "$PID pidfile_is_stale\n" if $DEBUG;
33 # kill isnt portable
34 if ($^O ne 'MSWin32')
35 {
36 my $pid = pidfile_read();
37 return kill 0, $pid;
38 }
39 return 0;
40 }
41  
42 sub pid
43 {
44 my $pid = $$;
45 # Win32 pids have a trailing newline?!
46 chomp $pid;
47 return $pid;
48 }
49  
50 sub pidfile_read
51 {
52 print "$PID pidfile_read\n" if $DEBUG;
53 open my $pidfile, '<', pidfile_name() or die 'Unable to open pidfile ' . pidfile_name();
54 my $pid = do { local($/);<$pidfile> };
55 close $pidfile;
56 chomp $pid;
57  
58 # avoid negative pid numbers and garbage
59 die "pidfile appears corrupted: $pid\n" unless $pid =~ /^[0-9]+$/;
60 return $pid;
61 }
62  
63 sub pidfile_clear
64 {
65 print "$PID pidfile_clear\n" if $DEBUG;
66 if (pid() eq pidfile_read())
67 {
68 unlink pidfile_name() or die "Unable to delete pidfile " . pidfile_name();
69 }
70 }
71 1;
72  
73 __END__