#!/usr/bin/perl # http://perlmonks.org/?node_id=1172353 use strict; use warnings; use IO::Select; $| = 1; my @data_files = qw( one two three four five six seven ); my $maxchildren = 4; my %data_for_handles; my $fh_A; if( open $fh_A, '|-' ) { # parent warn "pipe opened\n"; } else { # child print "program_A started\n"; print while ; print "program_A ended\n"; exit; } my $sel = IO::Select->new; while( @data_files or $sel->count ) { while( @data_files and $sel->count < $maxchildren ) { my $file = shift @data_files; if( open my $fh, '-|' ) { # parent $sel->add($fh); } else { # child $| = 1; warn "child $file started\n"; print "$file\n"; sleep 1; print "$file\n"; sleep 1; print "$file\n"; exit; } } if( $sel->count > 0 ) { for my $fh ($sel->can_read) { if(0 < sysread $fh, my $buffer, 16 * 1024 ) { $data_for_handles{$fh} .= $buffer; } else { print {$fh_A} delete $data_for_handles{$fh}; $sel->remove($fh); } } } } close $fh_A;