File Coverage

blib/lib/Proc/Find/Parents.pm
Criterion Covered Total %
statement 31 43 72.0
branch 6 16 37.5
condition 3 7 42.8
subroutine 4 4 100.0
pod 1 1 100.0
total 45 71 63.3


line stmt bran cond sub pod time code
1             package Proc::Find::Parents;
2              
3             our $DATE = '2014-12-05'; # DATE
4             our $VERSION = '0.62'; # VERSION
5              
6 1     1   1702 use 5.010001;
  1         3  
  1         31  
7 1     1   3 use strict;
  1         1  
  1         21  
8 1     1   3 use warnings;
  1         1  
  1         374  
9              
10             require Exporter;
11             our @ISA = qw(Exporter);
12             our @EXPORT_OK = qw(get_parent_processes);
13              
14             sub get_parent_processes {
15 1     1 1 538 my ($pid, $opts) = @_;
16 1   33     7 $pid //= $$;
17 1   50     5 $opts //= {};
18              
19 1         2 my %proc;
20 1 50 50     9 if (($opts->{method} // 'proctable') eq 'pstree') {
21             # things will be simpler if we use the -s option, however not all
22             # versions of pstree supports it. -l is for --long (to avoid pstree to
23             # cut its output at 132 cols)
24              
25 0         0 my @lines = `pstree -pAl`;
26 0 0       0 return undef unless @lines;
27              
28 0         0 my @p;
29 0         0 for (@lines) {
30 0         0 my $i = 0;
31 0         0 while (/(?: (\s*(?:\|-?|`-)) | (.+?)\((\d+)\) )
32             (?: -[+-]- )?/gx) {
33 0 0       0 unless ($1) {
34 0         0 my $p = {name=>$2, pid=>$3};
35 0         0 $p[$i] = $p;
36 0 0       0 $p->{ppid} = $p[$i-1]{pid} if $i > 0;
37 0         0 $proc{$3} = $p;
38             }
39 0         0 $i++;
40             }
41             }
42             #use Data::Dump; dd \%proc;
43             } else {
44 1         1 eval { require Proc::ProcessTable };
  1         503  
45 1 50       6474 return undef if $@;
46              
47 1         7 state $pt = Proc::ProcessTable->new;
48 1         1548 for my $p (@{ $pt->table }) {
  1         1656  
49 10         37 $proc{ $p->{pid} } = {
50             name=>$p->{fname}, pid=>$p->{pid}, ppid=>$p->{ppid},
51             };
52             }
53             }
54              
55 1         3 my @p = ();
56 1         2 my $cur_pid = $pid;
57 1         1 while (1) {
58 10 50       17 return if !$proc{$cur_pid};
59 10 50       18 $proc{$cur_pid}{name} = $1 if $proc{$cur_pid}{name} =~ /\A\{(.+)\}\z/;
60 10         9 push @p, $proc{$cur_pid};
61 10         7 $cur_pid = $proc{$cur_pid}{ppid};
62 10 100       15 last unless $cur_pid;
63             }
64 1         2 shift @p; # delete cur process
65              
66 1         5 \@p;
67             }
68              
69             # ABSTRACT: Find parents of a process (up to the root)
70              
71             __END__