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.

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
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.

In reply to Correct usage of fork and pipe? by CircusGimp

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.