Prakash
Prakash

Reputation: 600

Perl script shows different behavior inside cron job

I'm executing the following commands in a perl script.

#!/usr/bin/perl

my $MPSTAT="/usr/bin/mpstat";
my $GREP="/bin/grep";
my $FREE = "/usr/bin/free";
my $AWK = "/bin/awk";
my $cpu = `$MPSTAT | $GREP all | $AWK '{print (100 - \$12)}'`;
print "CPU is $cpu";

When I run this perl script manually it's getting executed properly and providing the proper CPU Usage in % (100 - Idle CPU).

But when I execute it as a cronjob it always prints 100 & it appears that $12 of awk is getting the value of 0. Any pointers on why it's behaving differently in cron would be helpful.

Upvotes: 1

Views: 462

Answers (2)

Prakash
Prakash

Reputation: 600

Found the solution using the hint provided by @WinnieNicklaus

mpstat is giving different results in cron.

Normal Execution:

04:53:18 PM  all   49.51    0.00    4.79    2.67    0.02    0.34    0.00    0.00   42.68

Inside Cron:

16:54:01   all   49.51    0.00    4.79    2.67    0.02    0.34    0.00    0.00   42.68

Since PM is not getting printed inside cron, when changed the argument for awk as $11 instead of $12 it started working.

Upvotes: 0

user507077
user507077

Reputation:

The main differences between running as a child of cron are:

  1. The user ID might be different (root vs normal user)
  2. The environment is nearly empty, at least pretty different

The second part often means that programs might output in a different language or number format due to the values of the LANG and LC_* environment variables which might be set for the normal user but not when run under cron (or vice versa).

Upvotes: 3

Related Questions