while (1) in server

T

Taras Kudla

hi to everybody,
i am new in perl and writing a simple server, and i have a problem,
for handling client connections i am using a while script, processor
usage during script running is 100%.
here is piece of code:
.....
my $socket=IO::Socket::INET->new(LocalPort =>
$port,Listen=>SOMAXCONN,Reuse=>1) or die "Cannot create listen socket:
$!";
......
sub handle_connection {
my $socket=shift;
....
while(1) {
my $answ=<$socket>;
}
}
can anyone suggest some other methods of connection handling or some
piece of code maybe.
thanks
 
J

Jens Thoms Toerring

Taras Kudla said:
hi to everybody,
i am new in perl and writing a simple server, and i have a problem,
for handling client connections i am using a while script, processor
usage during script running is 100%.
here is piece of code:
....
my $socket=IO::Socket::INET->new(LocalPort =>
$port,Listen=>SOMAXCONN,Reuse=>1) or die "Cannot create listen socket:
$!";
.....

I assume you have lines here left out with at least something like

$client = $socket->accept();
handle_connection( $client );
sub handle_connection {
my $socket=shift;
....
while(1) {
my $answ=<$socket>;
}
}

What you do here (at least as posted) is looping without taking
into account that the other side may already have closed the
connection. In that case the line
my $answ=<$socket>;

will return immediately with $answ being undefined. But you continue
to loop regardless, thus sending your program into an infinite loop
that will eat up all CPU time it can get. This could be avoided
by e.g. using instead

while ( my $answ = <$socket> ) {
....
}

This way the loop will terminate once $answ is undiefined (i.e. when
the other side has closed the connection).
can anyone suggest some other methods of connection handling or some
piece of code maybe.

That's a bit difficult since it's not clear to me what exactly you
want to achieve.
Regards, Jens
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,008
Latest member
HaroldDark

Latest Threads

Top