| 1 | |||
| 2 | package Proc::Parallel; | ||
| 3 | |||
| 4 | use strict; | ||
| 5 | use warnings; | ||
| 6 | use IO::Event::Callback; | ||
| 7 | use IO::Event; | ||
| 8 | use POSIX ":sys_wait_h"; | ||
| 9 | require Exporter; | ||
| 10 | |||
| 11 | our @ISA = qw(Exporter); | ||
| 12 | our @EXPORT = qw(start_command finish_commands); | ||
| 13 | our $VERSION = 0.601; | ||
| 14 | |||
| 15 | my %running; | ||
| 16 | |||
| 17 | sub start_command | ||
| 18 | { | ||
| 19 | my ($command, $input_callback, $eof_callback) = @_; | ||
| 20 | |||
| 21 | my $fh; | ||
| 22 | my $pid; | ||
| 23 | if (ref($command)) { | ||
| 24 | $pid = open $fh, "-|", @$command | ||
| 25 | or die "open @$command|: $!"; | ||
| 26 | } else { | ||
| 27 | $pid = open $fh, "-|", $command | ||
| 28 | or die "open $command|: $!"; | ||
| 29 | } | ||
| 30 | |||
| 31 | $running{$pid} = $command; | ||
| 32 | IO::Event::Callback->new($fh, | ||
| 33 | input => $input_callback, | ||
| 34 | eof => sub { | ||
| 35 | my ($handler, $ioe, $input_buffer_reference) = @_; | ||
| 36 | $eof_callback->($handler, undef, $input_buffer_reference) | ||
| 37 | if $eof_callback; | ||
| 38 | delete $running{$pid}; | ||
| 39 | $ioe->close(); | ||
| 40 | waitpid($pid, WNOHANG); | ||
| 41 | IO::Event::unloop_all() unless keys %running; | ||
| 42 | }, | ||
| 43 | ); | ||
| 44 | } | ||
| 45 | |||
| 46 | sub finish_commands | ||
| 47 | { | ||
| 48 | IO::Event::loop(); | ||
| 49 | } | ||
| 50 | |||
| 51 | 1; | ||
| 52 | |||
| 53 | __END__ |