Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Answer: Running subroutines asynchronously

by tachyon (Chancellor)
on Apr 05, 2002 at 00:43 UTC ( #156803=categorized answer: print w/replies, xml ) Need Help??

Q&A > subroutines > Running subroutines asynchronously - Answer contributed by tachyon

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( ); 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!";

Log In?

What's my password?
Create A New User
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (11)
As of 2018-06-25 18:42 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (128 votes). Check out past polls.