Skip to content

Instantly share code, notes, and snippets.

@leobalter

leobalter/1.pm Secret

Created June 12, 2018 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leobalter/d5c2817af13cfbe5e59b9ec958071352 to your computer and use it in GitHub Desktop.
Save leobalter/d5c2817af13cfbe5e59b9ec958071352 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
use strict;
use warnings;
use 5.8.8;
use IO::Handle;
use FindBin;
use Config;
my $Bin;
BEGIN {
$ENV{DBIC_OVERWRITE_HELPER_METHODS_OK} = 1;
unshift @INC, "$FindBin::Bin";
unshift @INC, "$FindBin::Bin/lib";
unshift @INC, "$FindBin::Bin/local/lib/perl5";
unshift @INC, "$FindBin::Bin/local/lib/perl5/$Config{archname}";
$ENV{LOAD_ROUTES} = 1;
}
use Parallel::ForkManager;
use Socket;
use DDP;
my $processes = 4;
my $pm = Parallel::ForkManager->new($processes);
my @files = ('a'..'z');
sub getFile {
return shift @files;
}
my @children;
my @parents;
# Open each process
FILES:
foreach (0..$processes-1) {
my $i = $_;
socketpair($children[$i], $parents[$i], AF_UNIX, SOCK_STREAM, PF_UNSPEC);
my $child = $children[$i];
my $parent = $parents[$i];
$child->autoflush(1);
$parent->autoflush(1);
$child->blocking(0);
$parent->blocking(0);
my $pid = $pm->start;
if ($pid) { # parent
# each child starts with a file;
my $file = shift @files;
chomp $file;
if ($file) {
print $child "$file\n";
}
while (<$child>) {
my $file = shift @files;
if (!$file) {
last;
}
chomp $file;
print $child "$file\n";
sleep(1);
}
$parent->close();
next FILES;
}
# children will start here
while (<$parent>) {
my $file = $_;
chomp $file;
print "child $i received $file\n";
sleep(int(rand(2)));
print $parent "2\n";
}
$child->close();
$pm->finish;
}
$pm->wait_all_children;
print "done\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment