AnyEvent::Socket
#!/usr/bin/env perl
use strict;
use warnings;
use 5.012;
use AnyEvent;
use AnyEvent::Socket;
my @pids;
foreach my $n ( 1 .. 5 ) {
my $pid = fork;
if ($pid) {
push @pids, $pid;
}
else {
say "forked";
do_task();
}
}
if (@pids) {
$SIG{INT} = sub {
foreach my $pid (@pids) {
kill( 2, $pid );
}
exit 0;
};
while (1) {}
}
sub do_task {
my $cv = AnyEvent->condvar;
$cv->cb(
sub {
say "done.";
}
);
my %count;
my @fh;
foreach my $n (1..10) {
$count{$n} = 0;
$cv->begin;
my $timer;
$timer = AnyEvent->timer(
after => 0,
interval => 1,
cb => sub {
tcp_connect '127.0.0.1', 11211, sub {
my ($fh) = @_;
if ( !$fh ) {
say "NG: $$ $n";
return;
}
my $io;
$io = AE::io $fh, 1, sub {
say "OK: $$ $n ";
print $fh "stats\n";
sleep(10);
#print $fh "quit\n";
undef $io;
};
if ( $count{$n}++ > 100 ) {
say "FIN: $$ $n";
$cv->end;
undef $timer;
}
}, sub { 1 };
}
);
}
$cv->recv;
}