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";
In reply to multiple fork() by Galen
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |