my $max = 5; while (my ($ip, $hostname) = each(%{$hosts->{'all'}})){ $i++; $c++; forkHost($ip); if($c == $max) { $c = 0; 1 while (wait() != -1); } } sub forkHost { my $target = shift; my $pid; next if $pid = fork; # Parent goes to next server. die "fork failed: $!" unless defined $pid; if (not $pid) { open COMMAND, "/execute/this/command |"; # Do some magic.. close COMMAND; exit; } }