2013-05-29 46 views
1

我正在開發一個腳本,用於基準測試和比較以各種語言(Perl,Java,R)編寫的用於相同目的的程序。我需要同時運行兩個子例程,一個使用Unix TOP命令,另一個執行程序。我試圖使用Parallel :: ForkManager。下面的代碼段我使用叉:如何在另一個孩子完成時退出子進程

sub parallelRun{ 

$commands[0]= sub{topExec}; 
$commands[1]= sub{masExec}; 

my $manager = new Parallel::ForkManager(2); 

for($i=0; $i <= $#commands; $i++) { 

     $pid = $manager-> start and next; 
     push(@pid,$pid); 
     $commands[$i](); 
     $manager-> finish; 

    } # For End 

    $manager->wait_all_children; 
    $manager-> finish($pid[0]); 
    undef(@pid); 

} # Sub End 

我需要完成topExec()(頂部執行)時masExec()結束,但是該腳本TOP命令後懸掛。

獎金問題:有沒有辦法讓masExec()執行的程序的系統pid在TOP命令中跟蹤它?現在,我正在使用Unix Top命令(sub topExec)中的列用戶和命令進行跟蹤。

對不起,對於任何語言錯誤(兩者都非本地))。

回答

2

kill(TERM => $pid[0]);


順便說一句,我不明白你爲什麼在這裏使用了P :: FM。你甚至不需要創建兩個孩子。

use POSIX qw(_exit); 

sub parallelRun { 
    my $pid = fork(); 
    die if !defined($pid); 

    if (!$pid) { 
     topExec(); 
     _exit(0); 
    } 

    masExec(); 
    kill(TERM => $pid); 
    waitpid($pid, 0); 
} 

一些Perl的技巧:

始終使用use strict; use warnings;。對於初學者,你有許多未申報的變數。

  1. $commands[0]= sub{topExec}; 
    $commands[1]= sub{masExec}; 
    

    應該

    my @commands = (\&topExec, \&masExec); 
    

    (聲明數組,不會產生不必要的匿名潛艇。)

  2. for(my $i=0; $i <= $#commands; $i++) { 
        ... $commands[$i] ... 
    

    應該是簡單

    for my $i (0..$#commands) { 
        ... $commands[$i] ... 
    

    甚至

    for my $command (@commands) { 
        ... $command ... 
    
  3. undef(@pid); 
    

    完全是不必要的。這是沒有正確申報@pid的症狀。

相關問題