Galen has asked for the wisdom of the Perl Monks concerning the following question:
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";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: multiple fork()
by Dominus (Parson) on Apr 16, 2001 at 20:40 UTC | |
by Galen (Beadle) on Apr 16, 2001 at 20:48 UTC | |
by tilly (Archbishop) on Apr 16, 2001 at 21:07 UTC | |
by Galen (Beadle) on Apr 16, 2001 at 21:20 UTC | |
by Dominus (Parson) on Apr 16, 2001 at 22:50 UTC | |
| |
by Dominus (Parson) on Apr 16, 2001 at 22:46 UTC | |
|
Re: multiple fork()
by spaz (Pilgrim) on Apr 16, 2001 at 21:10 UTC | |
|
Re: multiple fork()
by Rhandom (Curate) on Apr 16, 2001 at 22:37 UTC | |
by Rhandom (Curate) on Apr 16, 2001 at 23:10 UTC | |
by tye (Sage) on Apr 16, 2001 at 23:41 UTC | |
by Dominus (Parson) on Apr 17, 2001 at 03:55 UTC | |
by tye (Sage) on Apr 17, 2001 at 05:33 UTC | |
by Rhandom (Curate) on Apr 17, 2001 at 00:29 UTC | |
by tye (Sage) on Apr 17, 2001 at 00:32 UTC | |
| |
|
Re: multiple fork()
by ftforger (Sexton) on Apr 16, 2001 at 21:49 UTC | |
|
Re: multiple fork()
by traveler (Parson) on Apr 17, 2001 at 00:04 UTC |