#!/usr/bin/perl -w

use strict;
use Socket;
use IO::Handle;
use IO::Select;


# Spawn Children
my $read_select = IO::Select->new;
my $write_select = IO::Select->new;

for (my $child = 1 ; $child <= 40 ; $child++) {
	#print "starting process # $child\n";
  my ($child_fh,$parent_fh) = (IO::Handle->new, IO::Handle->new);
  socketpair($child_fh, $parent_fh, AF_UNIX, SOCK_STREAM, PF_UNSPEC)
    or die "socketpair failed: $!";
  
  $child_fh->autoflush;
  $parent_fh->autoflush;
  
  if (my $pid = fork) {
    close $parent_fh;
    $write_select->add($child_fh);
  } else {
    # Child code
    die "cannot fork: $!" unless defined $pid;
    close $child_fh; close STDIN; close STDOUT;
    
    while(defined(my $zone = <$parent_fh>)) {
    	chomp $zone;
    	print $parent_fh "pid $pid got code $zone\n";
    }
    exit 0;
  }
}

my $count = 0;

while (1) {
	my ($readable,$writable) = (IO::Select->select($read_select, $write_select, undef));
	
	#if (@$writable) {
	#	my $write_fh = shift @$writable;
	#
	if (@$writable and $count < 50) {
		$count++;
		my $write_fh = shift @$writable;
		print $write_fh "coucou$count\n";
		print "sending coucou$count\n";
		$write_select->remove($write_fh);
		$read_select->add($write_fh);
	}
	
	if (@$readable) {
		my $read_fh = shift @$readable;
		my $str = <$read_fh>;
		print $str;
		$read_select->remove($read_fh);
		$write_select->add($read_fh) if defined $write_select;
	}
	last if not defined $write_select;
}
