I have a cgi script that takes a selected list of network elements, telnets to them, issues a command and then echo's the response back to a web page. It works great, but I have one last functionality to add that is causing me headaches. When the list of elements is long, I can't afford to do each sequentially, because it takes 30 seconds or so for each element. The user sits there forever waiting for data to be returned. I want to use fork() to solve this problem. Imagine I have 20 elements - I want to telnet out to each of them simultaneously and gather data, and return the data when all 20 are completed. If done simultaneously with fork(), this should only require about 30 seconds, as opposed to 10 minutes if done sequentially.
I'm not sure how to approach this problem. I started by building something very simple - a script to read 3 text files and echo their contents back to the command line:. I stored the filenames in an array in order to mimic the way I read a list of network elements from an array. If I can get this to work, I should be able to use the same logic in my network code.
#!/usr/bin/perl
# forkit.pl
# This is my training script on fork. I will attempt to read and echo
+ data
# from three files simultaneously. The files are: file1, file2, file3
use CGI qw(:standard);
# Here is an array containing the names of the files that I will open
@files = ("file1", "file2", "file3");
# Let's show that we have correctly stored the filenames
print "\nThe files I will be looking at are:\n\n";
foreach (@files) {
print "$_\n";
}
print "\n";
# OK now I will open these files and echo their contents sequentially
# without using fork() ---
foreach (@files) {
open(EP,$_);
print "\nI just opened $_\n";
while (<EP>) {
chomp;
print "Contents of this file: $_\n";
}
}
print "\n";
# And now, do the same thing using fork()
I realize that I need to set up a condition so that each fork knows who it is based on the PID and executes appropriately. But, I'm getting some strange behavior. I would have thought it would simply be - foreach file, fork and if you are the child read the file and echo contents. Not so easy though... I am apparently forking more than I should. Also, I'm not even grabbing the contents of the files with the code below. What am I doing wrong?
foreach (@files) {
open(EP,$_);
$pid = fork();
if ($pid == 0) {
print "\nI just opened $_\n";
while (<EP>) {
chomp;
print "Contents of this file: $_\n";
}
} else {
print "This is the parent process\n";
}
}
print "\n";