Perl : CRTL C ignored when calling subroutine instead of exiting

标签 perl

所以脚本是这样的:

use strict;
use warnings;
use Term::ReadLine;

$SIG{'INT'} = 'INT_handler';
sub INT_handler {
  print "[+] Abording\n";
  home();
}

my $term = Term::ReadLine->new('Simple Perl calc');

sub home {

  my $prompt = "\$> ";
  my $OUT = $term->OUT || \*STDOUT;

  while ( defined ($_ = $term->readline($prompt)) ) {
    my $com = $_;
    print $com."\n";
    if ($com eq 'exit') {
        exit;
    }
  option(); # another subroutine when the input is transferred to
  }
}

home();

我得到了什么:
$>                                                                              
[+] Abording
$> # I pushed CRTL C but nothing shows                                                                             
$> # same here

我想要实现的是能够去home()不退出,保留$SIG{'INT'}在职的。

我尝试了一些其他方法(标签,使用 if 语句),但它会花费太长时间,因为输入用于长进程

最佳答案

您不应调用 home()在您的信号处理程序中。

只需设置一个您在输入循环中检查的标志。当$term->readline()返回,因为它被 CTRL-C 中断,检查标志是否设置,重置它并继续循环。

这是您更新的代码:

#!/usr/bin/perl
use strict;
use warnings;

use Term::ReadLine;

$SIG{'INT'} = 'INT_handler';
my $interrupted;
sub INT_handler {
    $interrupted++;
}

my $term = Term::ReadLine->new('Simple Perl calc');

sub home {
    my $prompt = "\$> ";
    my $OUT = $term->OUT || \*STDOUT;

    while ( defined ($_ = $term->readline($prompt)) || $interrupted ) {
        if ($interrupted) {
            $interrupted = 0;
            print "\n[+] Aborting\n";
            next;
        }
        my $com = $_;
        print $com."\n";
        if ($com eq 'exit') {
            exit;
        }
    }
}

home();

exit 0;

测试输出:

$ perl dummy.pl
$> test
test
$> ^C

[+] Aborting
$> ^C

[+] Aborting
$> sdasd^C

[+] Aborting
$> exit
exit

注意:似乎还有一个问题:您需要按回车键才能获得提示。可能与 Term::Readline 的方式有关作品。

关于Perl : CRTL C ignored when calling subroutine instead of exiting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54483979/

相关文章:

python - 在不创建序列文件的情况下运行 BLAST (bl2seq)

Perl 按模式匹配对数组进行排序

perl - 拆分数字和百分号进行比较

perl - 在 Perl 中生成引用第 3 方插件函数的 Excel 电子表格

javascript - 在 JavaScript 中打印哈希表 session 变量

perl - 如何卸载 Perl 模块?

regex - 如何使用正则表达式限制在 perl 上找到的匹配项?

php - 我什么时候应该使用 Perl CGI 而不是 PHP(反之亦然)?

python - 计算非常小的值的-log10

perl - 我可以访问 mac os x automator 中的 __DATA__ 部分吗