Price, Jason wrote:
> Not sure if this is the right list for this - if it's not, please
> direct me to the proper list.
You've come to the right place.
>
> Anyway, I'm trying to get my hands around forking, and was hoping you
> all could help me out. Basically, I'm trying to find a way to fire
> off a remote script on numerous boxes in parallel, returning their
> results to the parent script. Here's the basic flow I'm after:
>
> 1. User brings up web page for an on-demand report. Provides user
> input, hits submit, which fires off the parent script.
> 2. Parent script takes user input, and fires off a remote script
> located on all servers provided by user input.
> 3. Remote scripts return results to an array in the parent script.
> 4. Parent script compiles results and formats output for web display.
>
> The process currently works, but runs each remote server in series,
> which takes a considerable amount of time. I've had a hell of a time
> finding a good explanation of forking, and I only seem to be able to
> figure out how to fork one process at a time. I'm also unsure if the
> parent can utilize variables populated in a child, or if they're
> completely independent after the fork.
No. The parent cannot see any variables in the child. You need to use some
form of IPC to communicate between the processes. I would suggest using a
pipe. Here's an example of a parent that forks off three children, and then
reads data back from the children through a common pipe:
#!/usr/bin/perl
use strict;
$| = 1;
my $nc = 3; # number of children to create
pipe READER, WRITER; # pipe for communication
for my $c (1 .. $nc) {
# create a child process
defined(my $pid = fork) or die "Couldn't fork: $!";
next if $pid; # parent loops to create next child
# child does it's thing and writes back to parent through pipe
close READER;
select WRITER;
$| = 1;
print "Hello, I am child $c, and my PID is $$\n";
sleep rand(5) + 1;
print "Goodbye from child $c\n";
exit; # child exits (IMPORTANT!)
}
# parent reads from children
# pipe will close when last child exits
close WRITER;
while(<READER>) {
print $_;
}
1 while wait() > 0; # reap all exit statuses
Sample output:
$ perl myscript.pl
Hello, I am child 1, and my PID is 16774
Hello, I am child 2, and my PID is 16775
Hello, I am child 3, and my PID is 16776
Goodbye from child 2
Goodbye from child 1
Goodbye from child 3
If you need explanation of any of that, let me know.
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>