On Dec 10, 2003, at 3:52 PM, Dan Anderson wrote:

I am learning about forks, so I tried the following code to make sure I
had everything down:

Still don't believe me about Network Programming with Perl, eh? Did I mention that it covers forking well? <laughs>


Basic idea of fork:

if ($pid = fork()) {    # TWO processes will continue from write here
        # in parent process
} else {
        # in child process
}

#! /usr/bin/perl

use strict;
use warnings;

my $counter = 1;
my $pid = 0;

while ($counter < 50) {
  if ($pid = fork) {

Again, TWO processes will go forward from this point.


    open ("FORKED", ">./fork/$counter")
      or die("COULD NOT OPEN FORK");
    print FORKED $counter;
    close("FORKED");
    $SIG{CHLD} = "IGNORE";
  }

And here's the problem, with no else, they'll do the exact same thing! Loop and fork() again. You're spawning some serious processes my friend.


Use fork() when you want to do two things at once. Do one inside the if and the other in the else.

Hope that helps.

James

  $counter++;
}

I figured this would write 49 files relatively quickly and that would be
the end of it. Running it DOSes a 1Ghz PIII Box I have takes 20 minutes
-- during which time /nothing/ else can be done, i.e. a DOS. Oddly
enough, putting the limit on counter down to 5 runs in less then 0.02s.


So what am I doing wrong?

-Dan


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




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