开发者

How to run in parallel two child command from a parent one?

开发者 https://www.devze.com 2023-01-31 12:57 出处:网络
I need to run two perl scripts from one in parallel. How can I accomplish this? Currently, I have a file 开发者_开发技巧with

I need to run two perl scripts from one in parallel. How can I accomplish this?

Currently, I have a file 开发者_开发技巧with

system("perl command1.pl command2.pl"); 

Commands are executed in sequence and until command1.pl is done command2.pl won't run.

I would like to run the two commands simultaneously.

PLEASE HELP!


`perl command1.pl &`;

`perl command2.pl &`;

..or use the perl fork() function

perldoc -f fork

..or use perl threading

perldoc threads

Or just use a shell script:

#!/bin/sh
./command1.pl &
./command2.pl &


Depends on the command interpreter. In Windows you use the start command to just launch a process without waiting. In most *nix command interpreters as I recall the relevant notation is to add an ampersand & at the end of the command.


You could use a piped open to the process, ala

use 5.013;
use warnings;
use autodie;

open my $cmd1_fh, '-|', 'dir';
open my $cmd2_fh, '-|', 'cls';

Or, if you don't care about the output, fork and then exec:

my @child_pids;
for my $cmd ('dir', 'cls') {
    defined(my $child_pid = fork()) or die "Couldn't fork: $!";
    if ($child_pid == 0) {
        exec $cmd;
    } else {
        push @child_pids, $child_pid;
    }
}

for my $pid (@child_pids) {
   waitpid($pid, 0);
}

(If you do care about the output, fork and then backtick?)

Or use threads (I'm not proud of this example, and I haven't even written it yet. Look up an example using Thread::Queue for something much less awful)

use threads;

my @threads;

for my $cmd ('dir', 'cls') {
    push @threads, threads->create(sub { system @_ }, $cmd);
}

$_->join for @threads;

There's also several modules that help you out with this one, such as Parallel::ForkManager and Win32::Job.


Depending on your skill level and what you want to do, you might be interested in POE::Wheel::Run.

0

精彩评论

暂无评论...
验证码 换一张
取 消