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

I am trying to run multiple proccesses at the same timeand I do not care about the order in which they run or whether they wait for eachother. Basically, I am trying to replicate what I would get from typing: "MyProgram &" multiple times at the command line. There is probably some very simple solution to this problem that I am forgetting about, but either way, I can;t figure out how to do it. I have tried using backticks, but the program waits for the process within the ticks to end before continuing on and launching teh next process. I think that I might be able to use exec and fork, but I am not sure exactly how I would use them to accomplish my task. Thanks, Jeff

Replies are listed 'Best First'.
Re: Launching multiple processes
by Paladin (Vicar) on Jan 06, 2004 at 22:54 UTC
    Take a look at Parallel::ForkManager. It takes care of all the forking and execing for you, and gives you good control over the child processes.
Re: Launching multiple processes
by dominix (Deacon) on Jan 06, 2004 at 23:48 UTC
    check this column from merlyn it's a good starting point, there is a clear explanation of process launching and control.
    --
    dominix
Re: Launching multiple processes
by Roger (Parson) on Jan 06, 2004 at 23:06 UTC
    Quick solution using fork and exec.
    my $program = '/bin/ls'; my $num_children = 5; $SIG{CHLD} = 'IGNORE'; for (1..$num_children) { defined ( my $pid = fork ) or die "Can not fork!"; if (!$pid) { # in child process exec $program; } }
    Update: fixed the logical bug with fork, if fork returns pid of 0 (parent) the code would die too. undef and 0 both evaluates to false. Thanks to borisz to point out below. Zaxo is right too. ;-)

      the fork line should be written as
      defined ( my $pid = fork ) or die "Can not fork!";

      Another bug: You have the makings of a fine fork bomb. If I calculate right, you'll get 20 instances of /bin/ls from that. Call the child program with exec or else exit after system.

      Don't forget to zombie-proof it with wait or $SIG{CHLD), either.

      After Compline,
      Zaxo

Re: Launching multiple processes
by dpuu (Chaplain) on Jan 06, 2004 at 23:47 UTC
    The simplest way is probably to do precisely the thing that you want to emulate:
    system "MyProgram &";
    --Dave
    Opinions my own; statements of fact may be in error.
      Thanks for the simple idea. I assumed that since a & between backticks didn't work, it wouldn't work with system() either. Jeff