Arun Shankar Arun Shankar - 11 months ago 46
Linux Question

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 ?


use Expect;

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

[ qr/.*\?/i, #/
sub {
my $self = shift;

[ qr/password:/i, #/
sub {
my $self = shift;
#$expect->expect(1500,'-re', 'Mails marked as moved successfully\.$');

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

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

Answer Source

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 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);

for (1..5){
    $pm->start and next COMMANDS;



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