1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| #!/usr/bin/perl -w
use strict;
use diagnostics;
package TESTE;
use Parallel::ForkManager;
use IPC::PubSub;
use vars qw($pub $sub);
sub new
{
my $this = {};
$this->{IPC} = IPC::PubSub->new(DBM_Deep => 'channel.txt');
$pub = $this->{IPC}->new_publisher("#perl6","#moose");
bless($this,shift);
return $this;
}
sub run
{
# define publisher
#$pub = $_[0]->{IPC}->new_publisher("#perl6","#moose");
my $pid = fork();
if ($pid)
{
$sub = $_[0]->{IPC}->new_subscriber("#father");
while (1)
{
eval {
my @msgs = $sub->get('#perl6');
if ( scalar @msgs > 0)
{
print "$msgs[0]->{gna}\n";
}
};
}
}
else
{
my @names = qw( Fred Jim Lily Steve Jessica Bob Dave Christine Rico Sara );
# hash to resolve PID's back to child specific information
my $pm = new Parallel::ForkManager(5);
# Setup a callback for when a child finishes up so we can
# get it's exit code
$pm->run_on_finish(
sub { my ($pid, $exit_code, $ident) = @_;
# print "** $ident just got out of the pool ".
# "with PID $pid and exit code: $exit_code\n";
}
);
$pm->run_on_start(
sub { my ($pid,$ident) = @_;
# print "** $ident started, pid: $pid\n";
}
);
$pm->run_on_wait(
sub {
# print "** Have to wait for one children ...\n"
},
1,
);
foreach my $child ( 0 .. $#names )
{
my $pid = $pm->start("$names[$child]") and next;
# This code is the child process
# print "This is $names[$child], Child number $child\n";
eval {
# Add data to publisher!!
#$pub = $_[0]->{IPC}->new_publisher("#moose");
my $mp = "This is child $pid $names[$child] hello :)";
$pub->msg({ 'gna' => $mp });
};
#sleep ( 2 * $child );
# print "$names[$child], Child $child is about to get out...\n";
# sleep 1;
$pm->finish($child); # pass an exit code to finish
}
print "Waiting for Children...\n";
$pm->wait_all_children;
print "Everybody is out of the pool!\n";
}
}
package main;
import TESTE;
my $i = new TESTE;
$i->run; |
Partager