Hi,

  I'm trying to check a list of filenames to see if they actually exist. A 
problem arises if
the file is located on a known server but cannot be contacted (ping times out). 
It seems
that perl doesn't timeout, but waits for the stat call to return. My code is 
based on code
taken from the Perl Cookbook, modified only to add my 'long-time operations 
here". 
I've also tried using POSIX , sigaction, and forking, but couldn't get anything 
to work 
as I needed it. Basically I'm trying to have a quicker 'ping' operation. Any 
suggestions, 
please? Is it possibly just network errors?

output is:

% /tmp/test.pl
$/net/unknown_host/tmp/file.txt = undef;
tag 0 finished after 0
1 timed out after 30
$/net/known_host_2/tmp/file.txt = undef;
tag 2 finished after 0
$/net/known_host_3/tmp/file.txt = 0;
tag 3 finished after 0

code is:

#!/usr/bin/perl -w
use Data::Dumper;

$debug = 1;
$SIG{ALRM} = sub { die "timeout" };

$| = 1;

my @files = (
     '/net/unknown_host/tmp/file.txt',  # host unknown, so file doesn't exist
     '/net/known_host_1/tmp/file.txt',  # host unreachable, so file doesn't 
exist
     '/net/known_host_2/tmp/file.txt',  # host reachable, but file doesn't exist
     '/net/known_host_3/tmp/file.txt',  # host reachable, file exists
);

my $tag = 0;
for (@files) {
     my $result = chk($_, $tag++);
}

exit;

sub chk {
    my ($file, $tag) = @_;
    my $start = time();

    eval {
        alarm(1);
        # long-time operations here
        $stats = (-s $file);
        print Data::Dumper->Dump([$stats],[$file]) if $debug;
        alarm(0);
    };

    if ($@) {
        if ($@ =~ /timeout/) {
                                # timed out; do what you will here
            print "$tag timed out after ", time() - $start, "\n";
            return;
        }
        else {
            alarm(0);           # clear the still-pending alarm
            die;                # propagate unexpected exception
        } 
    } 
    print "tag $tag finished after ", (time() - $start), "\n";
}


 

       
---------------------------------
Looking for last minute shopping deals?  Find them fast with Yahoo! Search.

Reply via email to