CircusGimp has asked for the wisdom of the Perl Monks concerning the following question:
Hi codemonks,
just a, maybe boring, question to you. Is this a nice way to use fork and pipe, or should i change it?
The Task is to "ping" to a list of IP addresses, to check as fast as possible is the host alive or not. So i should do it parallel, i think. And I don't like to use for such a small job any external fancy IPC Cpan Module i like to use Perl internals, also for the sake of performance only 4 Child's parallel.
This will be my first use of fork, and i use pipe for the return of the values. If there exists other way's, more clean and/or elegant. I would prefer to hear it.use strict; use warnings; my @nums; my @pids; my $max = 4; my $children = 0; foreach my $i ( 0 .. 10 ) { # for all IP's now just 0 to 10 pipe( READER, WRITE ); my $pid; if ( $children == $max ) { $pid = wait(); $children--; } if ( defined( $pid = fork() ) ) { if ($pid) { $children++; print "Parent: forked child ($pid)\n"; push @pids, $pid; close(WRITE); my $num = <READER>; push @nums, ($num); close(READER); wait; } else { my $calc = 365 * $i; # just a example # on this place i will call the function, and capture the # return message print WRITE $calc; close(WRITE); exit; } } else { print "Error: failed to fork\n"; exit; } } for my $pid (@pids) { waitpid $pid, 0; } print "Numbers: @nums \n"; # on this place i will check the array of the return values
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Correct usage of fork and pipe?
by kennethk (Abbot) on Aug 07, 2014 at 15:41 UTC | |
|
Re: Correct usage of fork and pipe?
by salva (Canon) on Aug 07, 2014 at 14:20 UTC | |
|
Re: Correct usage of fork and pipe?
by Random_Walk (Prior) on Aug 08, 2014 at 07:56 UTC |