2011-03-10 29 views
2

我想用Perl腳本批量重複的操作,這是通過system()調用的。當出現問題並且我想中斷這個腳本時,^ C被shell捕獲,停止任何工作,並且Perl腳本快樂地走到下一個腳本。perl調用shell_interrupt^C停止shell,而不是perl

有沒有一種方法可以調用該作業,以便中斷將停止Perl腳本?

回答

5

您不檢查system的返回值。添加到您的父程序:

use autodie qw(:all); 

,並計劃將中止預期:

"…" died to signal "INT" (2) at … line … 

您可以捕獲這個異常與Try::Tiny以清理你自己,或者使用不同的消息。

9

您可以檢查$?看到由系統執行的命令是否從信號2(INT)死亡:

這裏的解析$?的一個完整的例子:

my $rc=system("sleep 20"); 
my $q=$?; 
if ($q == -1) { 
    print "failed to execute: $!\n" 
} elsif ($? & 127) { 
    printf "child died with signal %d, %s coredump\n", 
      ($q & 127), ($q & 128) ? 'with' : 'without'; 
} else { 
    printf "child exited with value %d\n", $q >> 8; 
} 
# Output when Ctrl-C is hit: 
# child died with signal 2, without coredump 

因此確切的檢查要爲:

my $rc=system("sleep 20"); 
my $q=$?; 
if ($q != -1 && (($q & 127) == 2) && (!($? & 128))) { 
     # Drop the "$? & 128" if you want to include failures that generated coredump 
    print "Child process was interrupted by Ctrl-C\n"; 
} 

參考:perldoc system$?處理和system()呼叫; perldoc perlvar有關$?的更多詳細信息