2016-01-03 115 views
2

我的意图是执行long.pl perl脚本,将不同路径作为参数,并且因为long.pl具有无限循环,因此在主脚本中它不会到达第二个路径。我想用fork来做,但我不确定它是否能解决我的问题!在另一个perl脚本中执行多个无限制perl脚本

有关完成任务的方法的一些信息将会有所帮助,请让我知道是否需要对问题说明进行任何说明。

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

回答

2

实例运行:

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

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

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."; 
+0

您错误地按下一个零到'@ pids' – Borodin

+0

嗯...我没有看到这一点,但你的观点是可以理解的:我想我应该看到一些零。 – 7stud

+0

啊...我现在看到他们了。 – 7stud

相关问题