2

My intention is to execute long.pl perl script with different path as an argument and since long.pl has indefinite loop such that in the main script it does not come to second path. I thought to use fork for doing it, but I'm not sure whether it will solve my problem or not!

Some information on the method of achieving the task would be helpful, and please let me know if you need any clarification on the problem statement.

#!/usr/bin/perl
use strict;
use warnings;

print localtime () . ": Hello from the parent ($$)!\n";

my @paths = ('C:\Users\goudarsh\Desktop\Perl_test_scripts','C:\Users\goudarsh\Desktop\Perl_test_scripts/rtl2gds'); 
foreach my $path(@paths){
    my $pid = fork;
    die "Fork failed: $!" unless defined $pid;
    unless ($pid) {
        print localtime () . ": Hello from the child ($$)!\n";
        exec "long.pl $path";  # Some long running process.
        die "Exec failed: $!\n";
    }
}

long.pl

#!/usr/bin/perl
use strict;
use warnings;
while(1){
    sleep 3;
    #do some stuff here 
}

1 Answer 1

2

Example run:

$ perl my_forker.pl
Done with other process.
Done with long running process.
Done with main process.

The following files must have executable permissions set:

long_running.pl:

#!/usr/bin/env perl

use strict;
use warnings;
use 5.020;

sleep 5;
say 'Done with long running process.';

other_process.pl:

#!/usr/bin/env perl

use strict;
use warnings;
use 5.020;

sleep 3;
say "Done with other process."

my_forker.pl:

use strict;
use warnings;
use 5.020;

my @paths = (
    './long_running.pl',
    './other_process.pl',
);

my @pids;

for my $cmd (@paths) {

    defined (my $pid = fork()) or die "Couldn't fork: $!";

    if ($pid == 0) { #then in child process
        exec $cmd;
        die "Couldn't exec: $!";  #this line will cease to exist if exec() succeeds
    }
    else {  #then in parent process, where $pid is the pid of the child
        push @pids, $pid;
    }

}

for my $pid (@pids) {
    waitpid($pid, 0)  #0 => block
}

say "Done with main process.";
Sign up to request clarification or add additional context in comments.

5 Comments

Hmm...I'm not seeing that, but your point is understood: I think I should be seeing some zeros.
@7stud now i am facing following problem -> i have modifed my_forker.pl script to such that it forks (execute) perl scripts with different inputs and i want them to run parallel but right now it is running sequentially which i do not want.
@Shantesh, Post a short example that demonstrates the problem.
@7stud here's the link for new question [link ](stackoverflow.com/questions/34702448/…) please have a look
@7stud did you have a look ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.