所以脚本是这样的:
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/