#!/usr/bin/perl use warnings; use strict; use IO::Select; # Number of simultaneous processes my $n = 5; # List of things to process my @p = (1..20); my $sel = IO::Select->new(); for my $pr (splice @p, 0, $n) { start_ps($sel, $pr); } my $cnt = 1; while ( my @ready = $sel->can_read() ) { for my $h (@ready) { local $_; my ($fh, $i) = @$h; while (<$fh>) { print "$i: $_"; } # Remove, then close!!! $sel->remove($fh); close $fh; start_ps($sel, shift(@p)) if @p; $cnt++; } print "-------------\n"; } sub start_ps { my ($t, $p) = @_; my $pid = open(my $fh, "-|"); die "Can't fork: $!" unless defined $pid; unless ($pid) { my @cmd = qw(/bin/echo Hello World); exec @cmd; die "Could not exec @cmd: $!"; } $t->add([$fh, $p]); }