需要在perl中并行运行命令

时间:2016-08-24 13:19:53

标签: linux perl

我有一个如下所述的脚本,我看到提到的命令为"需要运行的命令" (在for循环中)执行了一段时间,之后分叉执行命令的进程被终止,因此我的脚本中只有一部分需要运行" Command" (在for循环中)被执行。相反,我希望命令在" Command中运行" (在for循环中)所有并行运行,即如果for循环运行50次迭代,则需要并行执行50个不同的进程,并且不应在它们之间停止。有人可以就此提出建议吗?

#!/usr/bin/perl

use Expect;

sub hostuser_expect() {
    $expect= Expect->new;
    $expect->raw_pty(1);
    $expect->spawn($cmd)
    or die "Cannot spawn $cmd: $!\n";

    $expect->expect($timeout,
            [   qr/.*\?/i, #/
            sub {
                    my $self = shift;
                    $self->send("yes\r\n");
                    exp_continue;
                    }
            ]);

    $expect->expect($timeout,
            [   qr/password:/i, #/
            sub {
                    my $self = shift;
                    $self->send("$password\n");
                    exp_continue;
            }
    ]);
    #$expect->expect(1500,'-re', 'Mails marked as moved successfully\.$');
    #$expect->hard_close();
}

$timeout     = 5;
$password    = "changeme";

for ($i=1;$i<=50;$i++)   {
    $cmd="Command which needs to be run";
    print "Invoking script - $cmd\n";
    hostuser_expect();
    sleep(30);
}

1 个答案:

答案 0 :(得分:1)

我相信Parallel::ForkManager会做你想做的事。我不使用Expect,所以我简化了sub作为示例。我还添加了use strict;use warnings;,从子定义中删除了原型parens,并使用了C风格的for()循环实现。

只需将呼叫中的号码更改为Parallel::ForkManager->new()即可提高或降低任何时候执行的最大分叉数。

use warnings;
use strict;

use Parallel::ForkManager;

sub hostuser_expect {
    my $num = shift;
    print "in child $num\n";
}

my $pm = Parallel::ForkManager->new(5);

COMMANDS:
for (1..5){
    $pm->start and next COMMANDS;
    hostuser_expect($_);
    $pm->finish;
}

$pm->wait_all_children;

输出:

in child 1
in child 2
in child 5
in child 3
in child 4