turned into a dist
[scpubgit/System-Introspector.git] / lib / System / Introspector / Processes.pm
1 package System::Introspector::Processes;
2 use Moo;
3
4 use System::Introspector::Util qw(
5     handle_from_command
6     transform_exceptions
7 );
8
9 # args is automatically included, since it has to be last
10 my @Included = qw(
11     blocked
12     c
13     class
14     cputime
15     egid egroup
16     etime
17     euid euser
18     fgid fgroup
19     flags
20     fuid fuser
21     ignored
22     lwp
23     nice
24     nlwp
25     pgid pgrp
26     pid ppid
27     pri
28     psr
29     rgid rgroup
30     rss
31     ruid ruser
32     sgid sgroup
33     sid
34     size
35     start_time
36     stat
37     suid suser
38     tid
39     time
40     tname
41     wchan
42 );
43
44 sub gather {
45     my ($self) = @_;
46     my @names = (@Included, 'args');
47     return transform_exceptions {
48         my $pipe = $self->_open_ps_pipe;
49         my $spec = <$pipe>;
50         $spec =~ s{(?:^\s+|\s+$)}{}g;
51         my @fields = map lc, split m{\s+}, $spec;
52         my @rows;
53         while (defined( my $line = <$pipe> )) {
54             chomp $line;
55             $line =~ s{(?:^\s+|\s+$)}{}g;
56             my @values = split m{\s+}, $line, scalar @fields;
57             my %row;
58             @row{ @names } = @values;
59             push @rows, \%row;
60         }
61         return { processes => [ sort {
62             ($a->{args} cmp $b->{args})
63             ||
64             ($a->{pid} <=> $b->{pid})
65         } @rows ] };
66     };
67 }
68
69 sub _open_ps_pipe {
70     my ($self) = @_;
71     return handle_from_command sprintf
72         'ps -eo %s',
73         join(',', @Included, 'args');
74 }
75
76 1;
77
78 __END__
79
80 =head1 NAME
81
82 System::Introspector::Processes - Gather running processes
83
84 =head1 DESCRIPTION
85
86 Uses C<ps> to gather a list of all running processes.
87
88 =head1 SEE ALSO
89
90 =over
91
92 =item L<System::Introspector>
93
94 =back
95
96 =cut
97