On Dec 10, 2003, at 4:52 PM, Dan Anderson wrote:
I am learning about forks, so I tried the following code to make sure I had everything down:
#! /usr/bin/perl
use strict; use warnings;
my $counter = 1; my $pid = 0;
while ($counter < 50) { if ($pid = fork) { open ("FORKED", ">./fork/$counter") or die("COULD NOT OPEN FORK"); print FORKED $counter; close("FORKED"); $SIG{CHLD} = "IGNORE"; } $counter++; }
Two major problems:
o You are not closing your children when they are done with their tasks, meaning that they re-enter the while() loop and fork new children themselves. (this is why you fork-bombed your box)
o You are doing the work in the parent, not in the child
you want something like this:
$SIG{CHLD} = "IGNORE";
for my $counter(0...50) {
my $pid = fork();
if($pid == 0) { # child
open FORKED, ">./fork/$counter"
or die("COULD NOT OPEN ./fork/$counter");
print FORKED $counter;
close("FORKED");
exit; # critical to exit here, else this child will spawn new children itself
}
}
// George Schlossnagle // Postal Engine -- http://www.postalengine.com/ // Ecelerity: fastest MTA on earth
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>