簡體   English   中英

多線程perl腳本中的Control + C處理

[英]Control+C handling in multithread perl script

我是perl的新手,我在perl腳本中處理^ C時遇到問題。 當我在睡眠期間收到^ C后嘗試繼續執行腳本時,我只在$ FLAG = 2之前輸出; 之后沒有:

# perl test.pl 
sleeping...
^Cawaiking...  =  
#  

代替:

# perl test.pl 
sleeping...
awaiking...    ====                                              
some..
#

它接縫^ C正在殺死progres bar線程並且在它死后沒有動作但是可以在主線程中執行打印。 任何人都可以幫我解決這個問題嗎?

$SIG{INT} = 'IGNORE';
our $FLAG : shared = 1; 
...
sub call1{
    $FLAG = 1;
    my $pBar = threads->new(\&progressBarInit);
    $pBar->detach;
    print "sleeping...\n";
    sleep 5;
    print "awaiking...\n";
    $FLAG = 2;
    print "some..\n";
    return @result;
}

call1();

sub progressBarInit{
my $max = 50;
    my $counter = 1;
    while($FLAG == 1){
        progressBar( $counter, $max, 50, '=' );
        $counter++;
        if($counter > $max){$counter=1;}
        sleep 1;
    }
}

sub progressBar {
    my ( $counter, $max, $width, $char ) = @_;
    local $| = 1;
    printf "               %-${width}s\r", $char x (($width-1)*$counter/$max);
}

我認為問題是你在父設置中設置了信號處理程序。

根據這個: http//perldoc.perl.org/threads.html

需要在線程中設置信號處理程序,以獲得它們預期作用的信號。 這是取消線程的示例:

您可以使用信號進行通信,而不是使用標志:

sub progressBarInit    {
  # Thread 'cancellation' signal handler
  $SIG{'KILL'} = sub { threads->exit(); };
  $SIG{INT} = 'IGNORE';
  ...
}
...
# Signal the thread to terminate, and then detach
# it so that it will get cleaned up automatically
   my $pBar = threads->new(\&progressBarInit);    
    print "sleeping...\n";
    sleep 5;
    print "awaiking...\n";
    $pBar->kill('KILL')->detach();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM