为什么脚本终止时不调用对象析构函数?
我有一个这样的测试脚本:
package Test;
sub new { bless {} }
sub DESTROY { print "in DESTROY\n" }
package main;
my $t = new Test;
sleep 10;
在 sleep
返回之后(并且在程序终止之前)调用析构函数。但如果脚本使用 Ctrl-C 终止,则不会调用它。在这种情况下是否也可以调用析构函数?
I have a test script like this:
package Test;
sub new { bless {} }
sub DESTROY { print "in DESTROY\n" }
package main;
my $t = new Test;
sleep 10;
The destructor is called after sleep
returns (and before the program terminates). But it's not called if the script is terminated with Ctrl-C. Is it possible to have the destructor called in this case also?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如罗伯特提到的,你需要信号处理程序。
如果您需要的只是对象析构函数调用,则可以使用:
$SIG{INT} = sub { die "caught SIGINT\n" };
。As Robert mentioned, you need a signal handler.
If all you need is the object destructor call, you can use this:
$SIG{INT} = sub { die "caught SIGINT\n" };
.您必须设置一个信号处理程序。
沿着这些思路。然后在主循环中只需检查
$terminate
,如果已设置,则正常退出程序。发生的情况是 cntl-c 中断 sleep,调用信号处理程序设置 $terminate,sleep 立即返回,循环到顶部,测试 $terminate 并退出优雅地。
You'll have to set up a signal handler.
Something along these lines. Then in your main loop just check
$terminate
and if it's set exit the program normally.What happens is that the cntl-c interrupts the sleep, the signal handler is called setting
$terminate
, sleep returns immediately, it loops to the top, tests$terminate
and exits gracefully.