Pergunta

I have written following code to log ping RTT with timestamp for a server continuously. Script is working file at command line But my pain the log file Ping_10.112.114.11.txt is empty for which I see no error or warning or syntactical error in code.

Below is my code:

#!/user/bin/perl


use Net::Ping;
use Time::HiRes;
use strict;

open (LOG , ">Ping_10.112.114.11.txt") || die "Cannot create log file :$!";

print LOG "File is ready to write\n\n";
my $host ="10.112.114.11";
my $p = Net::Ping->new();       #tcp echo request for ping check
$p->hires();

do  
{   my ($ret, $duration, $ip) = $p->ping($host);
my $time = localtime;
my $dur = (int(1000*$duration))/1000;
print "$time\t$host is alive (packet RTT: $dur ms)\n";
print LOG "$time\t$host is alive (packet RTT: $dur ms)\n";
}   while(1);

#END

I have also tryed saving the output to a variable then sending it to filehandle for printing but unfortunately none of my efforts seems to be working fine.

my $output = ""$time\t$host is alive (packet RTT: $dur ms)\n";
print LOG "$output";

Can anyone please help me in highlighting my silly mistake as I have written many scripts which use same perl syntax but works fine.

Between my overall requirnment is to write a script which runs to record the RTT & connectivity of servers continuously with time stamp in a log file. Just like the output from Ping -t with additional timestamp value.

Thanks in advance :)

Foi útil?

Solução

The problem is likely to be that the output to your file is buffered, and you aren't waiting long enough for the buffer to be filled and flushed to the file. Enabling autoflush will fix this for you, and there are a few other issues with your code. This refactoring should do what you want.

use strict;
use warnings;

use Net::Ping;
use Time::HiRes;

my $host = '10.112.114.11';

STDOUT->autoflush;

open my $log, '>', "Ping_$host.txt" or die "Cannot create log file: $!";
$log->autoflush;

my $p = Net::Ping->new;
$p->hires;

while () {
  my ($ret, $duration, $ip) = $p->ping($host);
  my $event = sprintf "%s\t%s is alive (packet RTT: %.3fms)\n",
      scalar localtime, $host, $duration;
  print STDOUT $event;
  print $log $event;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top