Processes probe for ps output
[scpubgit/System-Introspector.git] / lib / System / Introspector / Processes.pm
1 package System::Introspector::Processes;
2 use Moo;
3
4 sub gather {
5     my ($self) = @_;
6     my $pipe = $self->_open_ps_pipe;
7     my $spec = <$pipe>;
8     $spec =~ s{(?:^\s+|\s+$)}{}g;
9     my @fields = map lc, split m{\s+}, $spec;
10     my @rows;
11     while (defined( my $line = <$pipe> )) {
12         chomp $line;
13         $line =~ s{(?:^\s+|\s+$)}{}g;
14         my @values = split m{\s+}, $line, scalar @fields;
15         my %row;
16         @row{ @fields } = @values;
17         push @rows, \%row;
18     }
19     return \@rows;
20 }
21
22 # args is automatically included, since it has to be last
23 my @Included = qw(
24     blocked
25     c
26     class
27     cputime
28     egid egroup
29     etime
30     euid euser
31     fgid fgroup
32     flags
33     fuid fuser
34     ignored
35     lwp
36     nice
37     nlwp
38     pgid pgrp
39     pid ppid
40     pri
41     psr
42     rgid rgroup
43     rss
44     ruid ruser
45     sgid sgroup
46     sid
47     size
48     start_time
49     stat
50     suid suser
51     tid
52     time
53     tname
54     wchan
55 );
56
57 sub _open_ps_pipe {
58     my ($self) = @_;
59     my $command = sprintf 'ps -eo %s', join(',', @Included, 'args');
60     open my $pipe, '-|', $command
61         or die "Unable to open pipe to '$command': $!\n";
62     return $pipe;
63 }
64
65 1;