在另一个perl脚本中执行多个不定的perl脚本

时间:2016-01-03 10:39:15

标签: perl unix fork

我的目的是以不同的路径作为参数执行long.pl perl脚本,因为long.pl具有无限循环,因此在主脚本中它不会进入第二条路径。我想用fork来做这件事,但我不确定它是否会解决我的问题!

有关完成任务的方法的一些信息会有所帮助,如果您需要对问题陈述进行任何澄清,请告诉我。

#!/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 个答案:

答案 0 :(得分:2)

示例运行:

'hp'

以下文件必须设置可执行权限:

long_running.pl:

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

other_process.pl:

#!/usr/bin/env perl

use strict;
use warnings;
use 5.020;

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

my_forker.pl:

#!/usr/bin/env perl

use strict;
use warnings;
use 5.020;

sleep 3;
say "Done with other process."