#!/usr/bin/perl -w

use IO::Socket;
use strict;
use POSIX qw(:sys_wait_h);

my $pid;

print "welcome to perl kenix server - perl version - by sam\n";

# socket creation
my $server = new IO::Socket::INET->new(
				       LocalPort => 15005,
				       Type => SOCK_STREAM,
				       Listen => 1)
    or die "impossible de devenir server : $@\n";

# zombies processes killing
$SIG{CHLD} = \&son_rescue;

# waiting for connections
while (my($client, $client_add) = $server->accept()) {

    # forking
    next if $pid = fork;
    close($server);
    my($port, $empip) = sockaddr_in($client_add);
    my $clip = inet_ntoa($empip);

    print "--- connected with $clip (pid is $$)\n";
    print $client "hello $clip ! i'm a perl kenix server clone (pid is $$)\n";
    
    # line management
    while (my $ligne=<$client>) {
	print "<$$> $ligne";
	print $client "$ligne";
	print $client "you are dead";
	if ($ligne =~ /^\/QUIT/i) {
	    print "received quit command by client\n";
	    print $client "/quit\n";
	    close($client);
	}
    }
    print "--- over with $clip (pid was $$)\n";
    
    # exiting forked server
    exit;
} 


# closing socket (cleaner :)
close($server);

# son_rescue (used to know dead forked server pid)
sub son_rescue {
    my $son;
    while(($son = waitpid(-1, WNOHANG)) > 0) {
	print "forked kenix server #$son is dead :(\n";
	}
    $SIG{CHLD} = \&son_rescue;
}

# writed by sam <sam@nova-mag.org>

