App/Chart/Proc/ChildPid.pm untested

filter: Statementstmt 0.0% 0 / 54 Branchbran 0.0% 0 / 14 Conditioncond 0.0% 0 / 5 MC/DCmcdc 0.0% 0 / 3 Subroutinesub 0.0% 0 / 11 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 93 CC 8 SCAR 27.9
CC
8
Cov
0%
kill_and_wait
42.0
kill
6.0
wait
6.0
CRAP 16.2
1 # Copyright 2008, 2009, 2010, 2011 Kevin Ryde
2  
3 # This file is part of Chart.
4 #
5 # Chart is free software; you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 3, or (at your option) any later version.
8 #
9 # Chart is distributed in the hope that it will be useful, but WITHOUT ANY
10 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11 # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
12 # details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with Chart. If not, see <http://www.gnu.org/licenses/>.
16  
17 package App::Chart::Proc::ChildPid;
18 use strict;
19 use warnings;
20 use Carp;
21 use Time::HiRes;
22 use POSIX qw(WNOHANG ECHILD);
23  
24 # uncomment this to run the ### lines
25 #use Smart::Comments;
26  
27  
28 sub new {
29 my ($class, $pid) = @_;
30 return bless { pid => $pid }, $class;
31 }
32  
33 sub DESTROY {
34 my ($self) = @_;
35 ## no critic (RequireInitializationForLocalVars)
36 local $?; # don't let waitpid() clobber prospective exit code during exit()
37  
38 ### ChildPid DESTROY
39 $self->kill_and_wait ('TERM');
40 }
41  
42 sub pid {
43 my ($self) = @_;
44 return $self->{'pid'};
45 }
46  
47 # sub poll {
48 # my ($self) = @_;
49 # return $self->kill(0) == 1;
50 # }
51  
52 sub kill_and_wait {
53 my ($self, $sig) = @_;
54 if (! $self->{'pid'}) {
55 $! = ECHILD;
56 return -1;
57 }
58 if ($self->kill ($sig) != 1) { return -1; }
59 Time::HiRes::usleep (10000);
60 my $sleeps = 0;
61 for (;;) {
62 my $status = $self->wait (WNOHANG);
63 if ($status != 0) { return $status; }
64 if ($sleeps >= 3) { last; }
65 sleep 1;
66 $sleeps++;
67 }
68 if ($self->kill ('KILL') != 1) { return -1; }
69 return $self->wait;
70 }
71  
72 sub kill {
73 my ($self, $sig) = @_;
74 my $pid = $self->{'pid'} || return 0;
75 if (! defined $sig) { $sig = 'TERM'; }
76 return kill ($sig, $pid);
77 }
78  
79 sub wait {
80 my ($self, $flags) = @_;
81 my $pid = delete $self->{'pid'}
82 || do { $! = ECHILD; return -1; };
83 if (! defined $flags) { $flags = 0; }
84 ### ChildPid wait: $pid
85 return waitpid ($pid, $flags);
86 }
87  
88 1;
89 __END__