FAQ
How do the to __END__ sections factor into this? Why does adding 1 allow 2
to say 'hi', then adding a third let them all work?
On Sun, Mar 27, 2016 at 11:26 PM, Lukas Mai wrote:

Am 28.03.2016 um 08:10 schrieb Chad Granum (via RT):
This script, should output "about to fork" and "Hi" 10 times. Instead it
prints "about to fork" 10 times, but "Hi" only once.

#!/usr/bin/env perl

BEGIN {
my $start = $$;
for ( 1 .. 10 ) {
my $pid = fork;
if ($pid) {
print "About to fork\n";
waitpid($pid, 0);
}
else {
last;
}
}
exit 0 if $$ == $start;
}

print "Hi\n";

Here is where it gets even MORE interesting, add these 3 lines to the end
of the script and it prints "Hi" twice:

__END__

print "Hi\n";

But wait, theres more! Add those 3 lines again, so it looks like this:

...
print "Hi\n";

__END__

print "Hi\n";

__END__

print "Hi\n";

And bam, it prints "Hi\n" all 10 times.

This looks like a filehandle fork bug to me, but I don't really know much
about these things.
Inherited filehandles share positions. BEGIN blocks run at parse time,
before the rest of the code has been read. The first child process will
read the rest of the code, parse it, print "Hi", and exit.

All other processes will continue parsing from where the last child left
off (because they share their read position in the source file).

It's nonintuitive but I'm not sure if this is even a bug.

--
Lukas Mai <plokinom@gmail.com>

Search Discussions

Discussion Posts

Previous

Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 3 of 5 | next ›
Discussion Overview
groupperl5-porters @
categoriesperl
postedMar 28, '16 at 6:10a
activeMar 28, '16 at 7:16a
posts5
users3
websiteperl.org

People

Translate

site design / logo © 2021 Grokbase