我是perl的新手,在我的perl脚本中处理^C时遇到了问题。当我在睡眠期间收到 ^C 后尝试继续执行脚本时,我只在 $FLAG = 2 之前输出;之后什么都没有:
# perl test.pl
sleeping...
^Cawaiking... =
#
而不是:
# perl test.pl
sleeping...
awaiking... ====
some..
#
接缝^C正在杀死progres条线程,并且在它死亡后没有任何操作,但可以在主线程中执行打印。谁能帮我解决这个问题?
$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}sr", $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();