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++;
> }
> 

[snip]

> So what am I doing wrong?

you are forking a lot more child than you think! what you essentially have 
is:

start with 1 process, fork:
        parent process
                parent goes back to fork:
                        parent
                                parent goes back to fork:
                                        parent
                                        child
                        child
                                child goes back to fork:
                                        parent
                                        child
        child process
                child goes back to fork:
                        parent
                                parent goes back to fork:
                                        parent 
                                        child
                        child
                                child goes back to fork:
                                        parent
                                        child
... etc

the number of process looks like:

1 before fork:
        2 after first fork:
                4 after second fork:
                        8 after third fork:
                                16 after fourth fork.
... etc

do the math for after 50 forks and you know how many process you have left 
in your machine and taking up all the memory and CPU time. you need to make 
sure the child does not go back to fork it's own child:

#!/usr/bin/perl -w
use strict;

$SIG{CHLD} = 'IGNORE';

for(1..50){
        my $pid = fork;
        die "no resource" unless(defined $pid);
        next if($pid);
        open(CHILd,">$_") || die $!;
        print CHILD $$,"\n";
        close(CHILD);
        exit; #-- kill child so it does go back
}

__END__

david
-- 
s,.*,<<,e,y,\n,,d,y,.s,10,,s
.ss.s.s...s.s....ss.....s.ss
s.sssss.sssss...s...s..s....
...s.ss..s.sss..ss.s....ss.s
s.sssss.s.ssss..ss.s....ss.s
..s..sss.sssss.ss.sss..ssss.
..sss....s.s....ss.s....ss.s

,....{4},"|?{*=}_'y!'+0!$&;"
,ge,y,!#:$_(-*[./<[EMAIL PROTECTED],b-t,
.y...,$~=q~=?,;^_#+?{~,,$~=~
y.!-&*-/:[EMAIL PROTECTED] ().;s,;,
);,g,s,s,$~s,g,y,y,%,,g,eval

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to