root/lib/Resmon/ExtComm.pm

Revision 7cb9f692ce04d65d7533b2f458138374c2fe6ed6, 1.2 kB (checked in by Eric Miller <internetjanitor@gmail.com>, 3 years ago)

Make sure command is defined in commhist before referencing it

  • Property mode set to 100755
Line 
1 package Resmon::ExtComm;
2
3 use strict;
4 use warnings;
5
6 use base "Exporter";
7 our @EXPORT_OK = qw/cache_command run_command/;
8
9 my %commhist;
10 my %commcache;
11 my %children;
12
13 sub cache_command {
14     my $expiry = pop;
15     my @command = @_;
16     my $command = join(" ", @command);
17
18     my $now = time;
19     if(defined($commhist{$command}) && $commhist{$command}>$now) {
20         return $commcache{$command};
21     }
22     $commcache{$command} = run_command(@command);
23     $commhist{$command} = $now + $expiry;
24     return $commcache{$command};
25 }
26
27 sub clean_up {
28     # Kill off any child processes started by run_command and close any pipes
29     # to them. This is called when a check times out and we may have processes
30     # left over.
31     while (my ($pid, $handle) = each %children) {
32         kill 9, $pid;
33         close ($handle);
34         delete $children{$pid};
35     }
36 }
37
38 sub run_command {
39     # Run a command just like `cmd`, but store the pid and stdout handles so
40     # they can be cleaned up later. For use with alarm().
41     my @cmd = @_;
42     my $pid = open(my $r, "-|", @cmd);
43     die "Can't run $cmd[0]: $!\n" unless defined($pid);
44     $children{$pid} = $r;
45     my @lines = <$r>;
46     delete $children{$pid};
47     close($r);
48     return join("", @lines);
49 }
50
51 1;
Note: See TracBrowser for help on using the browser.