3

我是 perl 新手,在我的 perl 脚本中处理 ^C 时遇到问题。当我在睡眠期间收到 ^C 后尝试继续执行脚本时,我只在 $FLAG = 2; 之前输出 之后什么都没有:

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

代替:

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

它接缝 ^C 正在杀死进度条线程,并且在它死后没有任何动作,但可以在主线程中执行打印。谁能帮我解决这个问题?

$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);
}
4

1 回答 1

0

我认为问题在于您在父级中设置了信号处理程序。

据此: 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();
于 2013-01-31T14:02:03.417 回答