Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Timeouting a socket script

by Thelonius (Priest)
on Dec 30, 2005 at 21:06 UTC ( [id://520065]=note: print w/replies, xml ) Need Help??


in reply to Timeouting a socket script

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); } }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://520065]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (2)
As of 2024-06-22 04:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.