【问题标题】:Control+C handling in multithread perl script多线程 perl 脚本中的 Control+C 处理
【发布时间】:2013-01-15 14:57:43
【问题描述】:

我是 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);
}

【问题讨论】:

  • 此代码在 Windows 上运行良好。任何^C 都会被忽略。
  • 也许these warnings 可能会有所帮助,在progressBar 中使用syswrite 而不是printf
  • @ring0,但信号处理程序没有调用progressBar。我不明白它会如何应用。

标签: multithreading perl unix keyboardinterrupt


【解决方案1】:

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

据此: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();

【讨论】:

  • 不幸的是它没有帮助。如果我放置 $SIG{INT} = 'IGNORE';进入 progressBarInit 而不是脚本的开头,它只是在按下 ^C 时终止它。 (您提到的所有更改都已应用)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-11
  • 2014-02-15
  • 2019-09-04
  • 2016-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多