简体   繁体   中英

Memory leak in perl server

I'm trying to write a multithreaded server with perl (Windows x64). When trying to connect to it from another computer, I found the memory and handle usage kept going up, even if I maintained only one connection at a time. And after thousands of trials it used up nearly all system memory. I can't figure out the reason.

Here is the server side:

use IO::Socket::INET;
use threads;

sub session_thread
{
    my $client_socket=$_[0];

    my $client_address = $client_socket->peerhost();
    my $client_port = $client_socket->peerport();
    print "connection from $client_address:$client_port\n";

    my $data = "";
    $client_socket->recv($data, 1024);
    print "$client_address:$client_port says: $data";

    $data = "ok";
    $client_socket->send($data);

    shutdown($client_socket, 1);
    $client_socket->close();
    threads->exit();
}

$| = 1;

my $socket = new IO::Socket::INET (
    LocalHost => '0.0.0.0',
    LocalPort => '7777',
    Proto => 'tcp',
    Listen => 5,
    ReuseAddr => 1
);
die "cannot create socket $!\n" unless $socket;
print "server waiting for client connection on port 7777\n";

while(1)
{
    my $client_socket = $socket->accept();
    threads->create('session_thread',$client_socket);
}

$socket->close();

Thanks.

You either have to wait for the thread to finish by joining it or tell Perl that you don't care about the thread's return value and that Perl itself should clean up the data once the thread exits. The latter seems to match your use case and is done by detaching .

Also note that using exit is not necessary in your example. You can simply return from the thread's subroutine normally. exit is used for ending a thread from a deeper nesting level within the program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM