Home > Archive > PERL Beginners > September 2007 > fork example
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
|
|
| Perllearner 2007-09-17, 7:00 pm |
| I am trying to get my mind around using fork()
I have a text file that has solid, liquid, and gas on it all on new
lines, how I understand fork() is if I wanted to do a print each
statement on each line in the file, fork() could do all at once with
parent and child processes.
I can get around doing this with a while loop i.e
#!/usr/bin/perl
use strict;
use warnings;
open(FILE, "text1.txt");
while (my $line = <FILE> ) {
print " The current state is $line"."\n";
}
How could I achieve the same with fork() ?
| |
| Tom Phoenix 2007-09-17, 10:00 pm |
| On 9/17/07, perllearner <cashback103@dodgeit.com> wrote:
> I am trying to get my mind around using fork()
>
> I have a text file that has solid, liquid, and gas on it all on new
> lines, how I understand fork() is if I wanted to do a print each
> statement on each line in the file, fork() could do all at once with
> parent and child processes.
Not exactly. You could fork a second process, but (with a few
exceptions) the two processes won't run "all at once", but
concurrently. That is, your central processor may at any given moment
be working for one of your processes, but typically not both. It's not
twice as fast to use two processes, in general.
The most common use of fork is in order to establish an environment
for a child process which will be launched (usually) via exec. The
child process runs concurrently with the parent.
A program could fork off several child processes, each one taking on a
particular task. The parent process could do other processing for a
while, then use wait() or waitpid() to wait for the child processes to
finish. The main reason to do this is when each separate process is
expected to be idle much of the time; if many processes all have work
for the CPU at the same time, some will normally have to wait.
Some people have more than one CPU, and may be hopeful that forking
several child processes will keep as many CPUs as busy as possible. It
might work, depending upon the algorithm and the system. But it might
not, and the overhead of multiple processes might not be overcome in
any case.
Additionally, using fork for concurrency adds a new set of potential
bugs and race conditions. Not to mention fork bombs! As with all power
tools, use fork with caution.
Does that help you any?
Cheers!
--Tom Phoenix
Stonehenge Perl Training
|
|
|
|
|