Re: simple multithread daemon

[email protected] ("Daniel Rychlik") Tue, 13 Nov 2007 07:17:02 -0600
Newsgroups perl.ithreads
Message-ID <60EF0688716ED54E87435A187FB6BD6A04C1EAFC@IS-MAILX.corp.securustech.net>
You are exiting the script when the disconnection happens.  You will need additional code for connection monitoring and clean up to achieve the desired result.
--------------------------
Respectfully,
Dan Rychlik
IT Projects Engineer



----- Original Message -----
From: jack ciabatta <[email protected]>
To: [email protected] <[email protected]>
Sent: Tue Nov 13 04:50:02 2007
Subject: simple multithread daemon

Hi,

I'm writing a simple tcp multithread daemon on a Linux i386 system.
For this moment the script is very short. I would like have 3 distinct
threads that answer to the clients. Every thread answers and exits
(with 'exit' client command) separately. At this moment when a thread
quit, kill all threads.

Thank you very much and regards


#!/usr/bin/perl -w

use strict;
use IO::Socket;
use threads;

$|=1;

my $socket = IO::Socket::INET->new (
	Proto     => 'tcp',
	LocalPort => 12345,
	Listen    => SOMAXCONN,
	Timeout   => 60,
	ReuseAddr => 1
) or die "Error: can't create listening socket : $!\n";

my $thr1 = threads->new(\&server,$socket);
my $thr2 = threads->new(\&server,$socket);
my $thr3 = threads->new(\&server,$socket);

$thr1->join;
$thr2->join;
$thr3->join;

exit(0);

sub server {
	my $socket = shift;
	my $tid = threads->tid();
	print "tid : $tid\n\n";

	while (my $connection = $socket->accept()){
		while (my $buf = <$connection>){
			chomp $buf;
			print "buf $buf\n";
			if ($buf =~ /exit/i){
				print "exit!\n";
				close $socket;
				exit(0);
			}
		}
	}

	close $socket;
	exit(0);
}