in reply to Question on Net::Ping and Threads

Your code is broken in many ways, but two things stand out.

  1. You are using (copies) of the same instance of Net::Ping in many threads. Not a good idea, so I've moved its creation inside the thread sub.
  2. You are closing the Net::Ping instance, which I've disabled.

This now "works", though your definition of what constitutes a "valid address" is pretty arbitrary:

#! /usr/bin/perl # to check ping from a file of hostnames using threads #use strict; use warnings; use threads; use threads::shared; use Net::Ping; use Time::HiRes; my $timeout = 5; print "\nEnter the host file name:"; chomp (my $host_file = <STDIN>); open (HOSTFILE, "<", $host_file) or die "\nOpen of $host_file failed. +$!"; my @host_array = <HOSTFILE>; close (HOSTFILE); print"\nEnter the output file name:"; chomp(my $out_file = <STDIN>); open (OUTFILE, ">", $out_file) or die "\n Open of $out_file failed.$!" +; my @threads; foreach $addr(@host_array){ chomp($addr); my $thr = threads->new(\&sub_ping,$addr); sleep(1); push(@threads,$thr); } foreach (@threads){ my $val = $_->join(); print "Trying to ping $val complete\n"; } sub sub_ping { my $host= shift; #to get $ARGV[0] my $ping_handle = Net::Ping->new("icmp",$timeout) or die "\n ping +unsuccessful. $!";; $ping_handle->hires(); if (($host =~ m([a-zA-Z]+\.\w+\.\w+)) || ($host =~ m(\d{1,3}\.\d{1 +,3}\.\d{1,3}\.\d{1,3}))) { ($ret, $lat, $ip) = ($ping_handle->ping($host)); if ($ret) { printf "$host \($ip\) responds to pings at %.2f msec.\n", +($lat//0)*1000; printf OUTFILE ("$host \($ip\) responds to pings at %.2f m +sec.\n",($lat//0)*1000); } else { printf "$host is NOT responding to pings. Time Taken %.2f +msec\n",($lat//0)*1000; printf OUTFILE ("$host is NOT responding to pings. Time ta +ken %.2f msec\n",($lat//0)*1000); } #$ping_handle->close(); } else { print "$host is NOT a valid address.\n"; print OUTFILE ("$host is NOT a valid address.\n"); } return $host; }

With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

The start of some sanity?

Replies are listed 'Best First'.
Re^2: Question on Net::Ping and Threads
by werdna (Initiate) on Dec 14, 2011 at 11:50 UTC

    Thank you... i am just a beginner in perl and wrote this as an assignment. I will change it as instructed.

    Thanks AJ