debiandude has asked for the wisdom of the Perl Monks concerning the following question:

Here is the problem. I want to write a progam that forks itself the specified number of times. And each of the forked programs runs another script a specified number of times. Here is what I tried but its not doing what I want, sigh
#!/usr/local/bin/perl -w # %W% %G% # Michael Petnuch, June 26, 2002 use strict; my %opt; %opt = get_args(); foreach ( 1 .. $opt{'F'}) { my $child; if(!defined($child = fork())) { die "Cannot fork: $!"; if(!defined($child = fork())) { die "Cannot fork: $!"; } elsif ($child == 0) { fork_it(); } else { sleep(2); next; } } ####### SUBS ####### sub fork_it { foreach( 1 .. $opt{'P'}) { exec("$opt{'E'} > /dev/null 2>&1"); } } sub help { my $error = shift; print $error, "\n" if(defined($error)); print STDERR "\n" ."Usage: $0 [-f number of childs] [-p number script processess +]\n" ." [-e what to execute] [-s how long to sleep inbetwe +en forks]\n\n" ."Example: $0 -f 2 -p 2 -e /usr/bin/tty_wrapper.sh -s 2\n\n"; exit(0); } sub get_args { my %opt; while ($_ = lc shift @ARGV) { if(/-f/) { $opt{'F'} = shift @ARGV; if(/-f/) { $opt{'F'} = shift @ARGV; } elsif (/-s/) { $opt{'S'} = shift @ARGV; } elsif (/-p/) { $opt{'P'} = shift @ARGV; } elsif (/-e/) { $opt{'E'} = shift @ARGV; } elsif (/(-|--)(h$|help$)/) { help(); } else { help("Invalid parameter $_"); } } return %opt; }

Replies are listed 'Best First'.
Re: Fork horror
by broquaint (Abbot) on Jul 08, 2002 at 15:42 UTC
Re: Fork horror
by robobunny (Friar) on Jul 08, 2002 at 15:45 UTC
    you seem to have the bit:
    if(!defined($child = fork())) { die "Cannot fork: $!";
    twice in a row, although that may have been an error in transcription. i would think it wouldn't run at all otherwise.
Re: Fork horror
by fruiture (Curate) on Jul 08, 2002 at 16:55 UTC
    not your question, but: have a look at Getopt::Std or better: Getopt::Long