James Marks wrote:
> Hi folks,

Hello,

> I don't know if this is a Perl or UNIX problem and I'm hoping you can
> help me figure that out.
> 
> I wrote a script that checks to see if the httpsd and mysqld processes
> are running on my server and to log the results of those tests.
> 
> When I run the script from the command line, the script prints to a log
> file the number of each of those processes that are running at the time
> of the script execution. When I run the same script from cron, however,
> it only prints a "1" for httpsd and mysqld.

cron has only a minimal environment.


> script output to log when run from the command line:
> 2006-08-12 21:10:20 httpsd 23 mysqld 33
> 
> script output to log when run from cron:
> 2006-08-12 21:11:05 httpsd 1 mysqld 1
> 
> Here's the cron entry:
> */15    *       *       *       *       perl
> /home/james/code/cron_code/httpsd_mysqld_check.pl

There is no need to put 'perl' in there because the first line of your script
is '#!/usr/bin/perl'.


> Here's the script:
> 
> #!/usr/bin/perl
> use warnings;
> use strict;
> 
> my $log_file = '/home/james/code/cron_code/httpsd_mysqld_log_file';
> 
> open FILE_OUT, ">> $log_file"
>     or die "Cannot open log file: $!";
> 
> select FILE_OUT;
> 
> (my $month, my $day, my $year, my $hour, my $minute, my $second) =
> (localtime)[4, 3, 5, 2, 1, 0];

my ( $second, $minute, $hour, $day, $month, $year ) = localtime;


> printf("%04s-%02s-%02s %02d:%02d:%02d ", $year+1900, $month, $day,
> $hour, $minute, $second);

The month field starts from 0 so you have to add 1 to it.

my $time = sprintf '%04d-%02d-%02d %02d:%02d:%02d',
           $year + 1900, $month + 1, $day, $hour, $minute, $second;


> my $httpsd_count = `ps -aux | grep -c httpsd`;
> my $mysqld_count = `ps -aux | grep -c mysqld`;

Your count will be off by one because the grep command is included in the
count.  No need to run ps twice and no need for the grep command or the shell:

open PS, '-|', '/bin/ps', 'aux' or die "Cannot open pipe from ps: $!";

my ( $httpsd_count, $mysqld_count );
while ( <PS> ) {
    $httpsd_count++ if /httpsd/;
    $mysqld_count++ if /mysqld/;
    }
close PS or warn $! ? "Error closing ps pipe: $!"
                    : "Exit status $? from ps";

print $time,
      ' httpsd ', $httpsd_count || 'NOT RUNNING',
      ' mysqld ', $mysqld_count || 'NOT RUNNING',
      "\n";


> Any ideas on why the same script has different results when run from the
> command line vs. from cron?

I tested your script from cron and from the command line and didn't see a
difference.



John
-- 
use Perl;
program
fulfillment

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to