Shankar Guru
Shankar Guru

Reputation: 1161

Need Commands to be run in parallel in perl expect

I have a script as mentioned below, I see the command mentioned as "Command which needs to be run" (in for loop) executes for some time and later the process which was forked to execute the command is killed and thus only part of my script in "Command which needs to be run" (in for loop) is executed. Instead, I want the command in "Command which needs to be run" (in for loop) to all run in parallel i.e. if the for loop runs for 50 iterations, 50 different process needs to be executing in parallel and none should be stopped in between. Could some one please suggest on this ?

#!/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);
}

Upvotes: 0

Views: 158

Answers (1)

stevieb
stevieb

Reputation: 9296

I believe Parallel::ForkManager will do what you want. I don't use Expect, so I've simplified the sub as an example. I've also added use strict; and use warnings;, removed the prototype parens from the sub definition, and changed from using a C-style for() loop implementation.

Just change the number in the call to Parallel::ForkManager->new() to raise or lower the maximum number of forks to be executing at any one time.

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;

Output:

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

Upvotes: 1

Related Questions