develooper Front page | perl.beginners | Postings from December 2002

how to use alarm() to properly time out a connection?

Thread Next
From:
Ian Zapczynski
Date:
December 20, 2002 09:58
Subject:
how to use alarm() to properly time out a connection?
Message ID:
3E035ADB.9080207@quarterleaf.com
Hello all,

I need to use alarm to time out a connection to an SFTP server if the 
connection hangs (I was able to reproduce such a hang using the Secure 
Shell Server for Windows, so I thought it would be nice if my script 
assumed this was a possibility).

I think I am not understanding the perldoc for alarm properly, because 
the following test script did not do what I want it to do:

#!/usr/bin/perl -w

use strict;

eval {
        while (1) {
                local $SIG{ALRM} = sub { die "alarm\n" };
                alarm 60;
        }
};

if ($@) {
        print "uh, I didn't time out" unless $@ eq "alarm\n"; 
}

In reality, I don't want such a loop that is always true - this is just 
my test case.  The real code looks more like:

eval {
                $sftp = Net::SFTP->new($FTPHOST, user=>$FTPUSER, 
password=>$FTPPASS);
                local $SIG{ALRM} = sub { die "alarm\n" };
                alarm 60;
};

if ($@) {
        &sendSNMP unless $@ eq "alarm\n"; 
}

When I run the test code with the endless while loop, the script never 
times out.  Can someone explain how I miswrote my script?

Unfortunately the hung SFTP connection is hard to reproduce 
consistently, so I want to be sure my code *should* work if such a 
situation occurs.  Please note that the SFTP connection must exist in an 
eval() so when it dies, it does not exit my script.  

Thanks!



Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About