natxo has asked for the wisdom of the Perl Monks concerning the following question:

using IPC::Cmd I am writing a nagios check that will warn whenever one of the systemd services is not running.

use IPC::Cmd qw[can_run run run_forked]; my $cmd = "systemctl --failed --no-legend"; my ( $success, $error_message, $full_buf, $stdout_buf, $stderr_buf ) = run( command => $cmd, verbose => 0 ); if ($success) { my $nr_els = @$full_buf; if ( $nr_els == 0 ) { print "OK: all systemd units in their desired state\n"; } else { print "WARNING: "; print "$nr_els systemd units not running\n"; for (@$full_buf) { print "$_\n"; } } }
Quite straight forward. I have killed -9 (yes, with signal 1 or 15 then they are not in a failed state, you need to really kill them) two services and then I run this and get this:
WARNING: 1 systemd units not running avahi-daemon.service loaded failed failed Avahi mDNS/DNS-SD Stack packagekit.service loaded failed failed PackageKit Daemon
Why do I get '1' instead of 2? When looping throught the elements of @$full_buf I get two lines of text, so I should also get '2' in $nr_els but I get '1'.

I must be missing something very basic ..., but I cannot see it. Thanks for your input!




Replies are listed 'Best First'.
Re: number of elements in array ref wtf
by haukex (Archbishop) on Jul 13, 2017 at 19:00 UTC
    Why do I get '1' instead of 2? When looping throught the elements of @$full_buf I get two lines of text, so I should also get '2' in $nr_els but I get '1'.

    Without having run the code, a quick guess: Are you sure $full_buf->[0] isn't just a single string with two lines in it? Use Data::Dump (or Data::Dumper with $Data::Dumper::Useqq=1;) to find out... (Basic debugging checklist)

      yes, spot on. Sorry for the noise.

        Hi,

        This 'noise' may point some other sufferer in the right direction in future.

        No need to apologize.

        J.C.