我是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);
}
答案 0 :(得分: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();