Created
September 21, 2012 14:45
-
-
Save wchristian/3761889 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use strictures; | |
use IPC::Open3 'open3'; | |
use Symbol 'gensym'; | |
# run some processes in parallel | |
# collect output | |
# no fork on non-*nix platforms | |
# pure perl | |
# no STDIN mangling | |
# works on *all* platforms | |
run(); | |
sub run { | |
my @tasks = map { { cmd => $_ } } ( | |
[qw( ls . )], [qw( ls .. )], | |
[ 'perl', '-e', 'sleep 4;print q[c]; warn q[d]' ], | |
[ 'perl', '-e', 'sleep 4;print q[a]; warn q[b]' ] | |
); | |
my $time = time; | |
run_tasks( @tasks ); | |
printf "%d s\n\n", time - $time; | |
print "$_->{out}$_->{err}$_->{exit}\n\n" for @tasks; | |
} | |
sub run_tasks { | |
my ( @tasks ) = @_; | |
for my $task ( @tasks ) { | |
my $pid = open3( undef, my $out, my $err = gensym, @{ $task->{cmd} } ); | |
@{$task}{qw( pid out err )} = ( $pid, $out, $err ); | |
} | |
for my $task ( @tasks ) { | |
waitpid $task->{pid}, 0; | |
$task->{exit} = $?; | |
for my $channel ( qw( out err ) ) { | |
{ | |
local $/ = ''; | |
$task->{$channel} = readline $task->{$channel}; | |
} | |
die "Error getting $channel: $!" if $!; | |
$task->{$channel} = '' if !defined $task->{$channel}; | |
} | |
} | |
return; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment