ivanatora has asked for the wisdom of the Perl Monks concerning the following question:

I have a network script running, but after some time it stops responding. The network connection is closed, but the script process is still running. I'm using IO::Socket::INET module to make a filehandle-like socket ;) How can I make the script to kill itslef if the network link is dropped? I tried adding option 'Timeout' when creating the new $socket object, but then the script wont run at all.

Replies are listed 'Best First'.
Re: Timeouting a socket script
by zentara (Cardinal) on Dec 30, 2005 at 20:23 UTC
Re: Timeouting a socket script
by Thelonius (Priest) on Dec 30, 2005 at 21:06 UTC
    Your question is a bit vague. Saying "it stops responding" could mean several things. Perhaps zentara's links will solve your problem.

    I've written an example TCP server which will kill a process after $timeout seconds or if the client closes the connection.

    You can test it with a web browser, e.g., connecting to http://yourserverhere:5050/ and then clicking the Stop loading button.

    If neither my nor zentara's answer helps you, post your actual code and a more precise description of what happens. (By the way, the correct English is "timing out", not "timeouting".)

    use IO::Socket::INET; use IO::Select; use Errno; use strict; $| = 1; my $timeout = 30; my $listen = IO::Socket::INET->new( Listen => 5, LocalPort => 5050, Proto => "tcp") or die "new sock error: $!\n"; my $alive; $SIG{CHLD} = sub { $alive = 0 }; while (1) { my $conn = $listen->accept; if (!$conn) { if ($!{EINTR}) { next } else { last } } print "Accepted\n"; while (<$conn>) { last if /^\r?\n$/; } print "After header\n"; $alive = 1; my $pid = fork; die "fork error: $!" unless defined $pid; if ($pid) { IO::Select->new($conn)->can_read($timeout); if ($alive) { print "killing child process\n"; kill 'KILL', $pid } else { print "Child already dead\n"; } } else { print $conn "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"; print $conn "<html><head><title>abort test</title></head>\n"; for (1 .. 100) { print $conn "<div>$_<br></div>\n"; sleep 1; } print $conn "</html>\r\n"; $conn->shutdown(2); close($conn); } }