http://www.perlmonks.org?node_id=156803


in reply to Running subroutines asynchronously

Sounds like a job for fork(). Fork a stack of kids to do the pinging and waiting in parallel.

Check out Non-linear sub-routine launching for more details.

#!/usr/bin/perl -w use strict; use POSIX ":sys_wait_h"; $|++; my @hosts = qw( www.perlmonks.com www.perl.com www.netscape.com ); my (@pids, $count); for my $host(@hosts) { sleep 1; # this limits to 1 kid per second, not actually required $count++; my $pid = fork(); push @pids , $pid; die "Fork failed\n" unless defined $pid; next if $pid; # get parent to reiterate and fork more kids my $reply = `ping -n 1 $host`; # get kids pinging, single ping print "I am child $count, pinged $host\n$reply\n\n"; exit; # kill child } # wait for kids to finish, no zombies on us my $kids; do { $kids = waitpid(-1,&WNOHANG); } until $kids == -1; print "Spawned $count kids, waited on @pids\nAll done!";