Processes probe for ps output
Robert 'phaylon' Sedlacek [Tue, 1 May 2012 22:10:23 +0000 (22:10 +0000)]
lib/System/Introspector/Processes.pm [new file with mode: 0644]

diff --git a/lib/System/Introspector/Processes.pm b/lib/System/Introspector/Processes.pm
new file mode 100644 (file)
index 0000000..0c08b72
--- /dev/null
@@ -0,0 +1,65 @@
+package System::Introspector::Processes;
+use Moo;
+
+sub gather {
+    my ($self) = @_;
+    my $pipe = $self->_open_ps_pipe;
+    my $spec = <$pipe>;
+    $spec =~ s{(?:^\s+|\s+$)}{}g;
+    my @fields = map lc, split m{\s+}, $spec;
+    my @rows;
+    while (defined( my $line = <$pipe> )) {
+        chomp $line;
+        $line =~ s{(?:^\s+|\s+$)}{}g;
+        my @values = split m{\s+}, $line, scalar @fields;
+        my %row;
+        @row{ @fields } = @values;
+        push @rows, \%row;
+    }
+    return \@rows;
+}
+
+# args is automatically included, since it has to be last
+my @Included = qw(
+    blocked
+    c
+    class
+    cputime
+    egid egroup
+    etime
+    euid euser
+    fgid fgroup
+    flags
+    fuid fuser
+    ignored
+    lwp
+    nice
+    nlwp
+    pgid pgrp
+    pid ppid
+    pri
+    psr
+    rgid rgroup
+    rss
+    ruid ruser
+    sgid sgroup
+    sid
+    size
+    start_time
+    stat
+    suid suser
+    tid
+    time
+    tname
+    wchan
+);
+
+sub _open_ps_pipe {
+    my ($self) = @_;
+    my $command = sprintf 'ps -eo %s', join(',', @Included, 'args');
+    open my $pipe, '-|', $command
+        or die "Unable to open pipe to '$command': $!\n";
+    return $pipe;
+}
+
+1;