tags:

views:

53

answers:

2

I have a basic perl HTTP server using HTTP::Daemon. When I stop and start the script, it appears that the port is still being listened on and I get an error message saying that my HTTP::Daemon instance is undefined. If I try to start the script about a minute after it has stopped, it works fine and can bind to the port again.

Is there any way to stop listening on the port when the program terminates instead of having to wait for it to timeout?

 use HTTP::Daemon;
 use HTTP::Status;

 my $d = new HTTP::Daemon(LocalAddr => 'localhost', LocalPort => 8000);

 while (my $c = $d->accept) {
    while (my $r = $c->get_request) {
       $c->send_error(RC_FORBIDDEN)
    }
    $c->close;
    undef($c);
 }

EDIT:

As per DVK's response, I tried calling $d->close() but am still getting the same error when trying to restart my script.

END { $d->close(); }
$SIG{'INT'} = 'CLEANUP';
$SIG{__WARN__} = 'CLEANUP';
$SIG{__DIE__} = 'CLEANUP';

sub CLEANUP {
    $d->close();
    undef($d);
    print "\n\nCaught Interrupt (^C), Aborting\n";
    exit(1);
}
A: 

Did you try $d->close() at the end of the program?

If not, try that. It's not documented in HTTP::Daemon POD example but the method should be available (inherited from IO::Socket)

Remember that you might need to be creative about where to call it, e.g. it might need to go into __DIE__ handler or END {} block

DVK
Yes, I called $d->close() in the END, INT, \__DIE__, and \__WARN__ blocks and am still getting the same error.
Trevor
A: 

I found a solution to my problem by setting ReuseAddr => 1 when creating the HTTP::Daemon.

my $d = new HTTP::Daemon(
    ReuseAddr => 1, 
    LocalAddr => 'localhost', 
    LocalPort => 8000);
Trevor