trippledubs has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

Can you explain why this script hangs? Thanks for looking.
#!/usr/bin/env perl use strict; use warnings; my $trials = 1000; sub bdayRuns { my $space = shift // 2**16; my $avg; TRIAL: for (1..$trials) { my %keys; for my $chance (1..$space) { my $r = int(rand($space)); if (++$keys{$r} > 1) { $avg+= $chance; next TRIAL; } } } $avg = $avg / $trials; return "Average collision out of $space: $avg : Runs: $trials\n"; } pipe(my $rh, my $wh); for (1..4) { my $pid = fork; if (!$pid) { #child print $wh " $$ - " . bdayRuns(365); exit; } } print "$_" while (<$rh>); 1 until wait == -1;

Replies are listed 'Best First'.
Re: forking script hangs
by oiskuu (Hermit) on Jun 10, 2015 at 20:44 UTC

    You forgot to close the $wh on parent side, so the pipe stays open forever.

    A close $wh; before the while (<$rh>) ought to fix it.

    Oh, and please do note that the writes aren't atomic—no guarantee the reports won't intermingle.

      ... and fork lacks an error check, too.

      (Yes, fork can fail. POSIX documents EAGAIN (temporary lack of resources or resource limits exceeded) and ENOMEM (out of memory). Linux also documents ENOSYS (not supported, e.g. on MMU-less hardware). The *BSDs follow POSIX.)

      Alexander

      --
      Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
        ahh I was thinking incorrectly the parent should stop blocking when no more messages in the pipe sort of like when you read a socket. Thanks for clarifying and links.
Re: forking script hangs
by MidLifeXis (Monsignor) on Jun 10, 2015 at 20:39 UTC

    What platform?

    --MidLifeXis