Skip to content

Instantly share code, notes, and snippets.

@yowcow
Created January 16, 2016 14:55
Show Gist options
  • Save yowcow/09cfbd2cfa828b0f82be to your computer and use it in GitHub Desktop.
Save yowcow/09cfbd2cfa828b0f82be to your computer and use it in GitHub Desktop.
Simple IPC with pipe
use common::sense;
pipe my $read, my $write;
my @pids;
for (1 .. 5) {
my $pid = fork // die "Failed: $!";
if ($pid) { # Parent
say "[Parent $$] Forked child: $pid";
push @pids, $pid;
}
else { # Child
close $read;
my $sec = int(rand(4) + 1);
sleep $sec;
print $write "[Child $$] Hello!! I've waited $sec seconds.\n";
exit;
}
}
close $write;
my @in = <$read>;
waitpid($_, 0) for @pids;
say "[Parent $$] All children exited";
print $_ for @in;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment