Re: simple multithread daemon

[email protected] ("jack ciabatta") Wed, 14 Nov 2007 12:13:50 +0100
Newsgroups perl.ithreads
Message-ID <[email protected]>
Mmhh... I'm trying with threads->exit();.. any suggests? Could be
useful a similar "simple, practical and complete" example on cpan? For
newbies. It would be great.

Regards,
Jack


my $port    = 2500;
my $timeout = 60;

$| =1;

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

while (my $client = $server->accept()) {
	my $thr = threads->create("listen_to_client", $client);
	my $thr1 = threads->create("stdin_to_client", $client);
	print "Client connected ", $thr->tid,"\n";
	$thr->detach;
	$thr1->detach;
}

exit(0);

sub listen_to_client {
	my ($client) = @_;
	my $tid = threads->tid();
	while (my $get = <$client>) {
		print "client ($tid) : $get";
		print $client $get;
	};
	print "Client closed\n";
	close $client;
}

sub stdin_to_client {
	my ($client) = @_;
	while (my $msg = <STDIN>) {
		print $client $msg;
		if ($msg =~ /exit/i){
			print "exit\n";
			close $client if $client;
			#threads->exit() if threads->can('exit');
			threads->exit();
		}
	}
	print "stdin thread ended\n";
}

2007/11/13, Jerry D. Hedden <[email protected]>:
> jack ciabatta wrote:
> > 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.
>
> First of all, upgrade to the lastest version of 'threads'
> and threads::shared from CPAN.
>
> Normally, a thread should 'return' and not 'exit'.  However,
> there is a whole section on this in the 'threads' POD called
> 'EXITING A THREAD'.
>