为什么脚本终止时不调用对象析构函数?

发布于 2024-08-28 11:55:33 字数 255 浏览 7 评论 0原文

我有一个这样的测试脚本:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

愁以何悠 2024-09-04 11:55:33

正如罗伯特提到的,你需要信号处理程序。
如果您需要的只是对象析构函数调用,则可以使用:

$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" };.

不再让梦枯萎 2024-09-04 11:55:33

您必须设置一个信号处理程序。

package Test;
sub new { bless {} }
sub DESTROY { print "in DESTROY\n" }

package main;

my $terminate = 0;

$SIG{INT} = \&sigint;

sub sigint { $terminate = 1; }

my $t = new Test;

while (1) {
    last if $terminate;
    sleep 10;
}

沿着这些思路。然后在主循环中只需检查 $terminate ,如果已设置,则正常退出程序。

发生的情况是 cntl-c 中断 sleep,调用信号处理程序设置 $terminate,sleep 立即返回,循环到顶部,测试 $terminate 并退出优雅地。

You'll have to set up a signal handler.

package Test;
sub new { bless {} }
sub DESTROY { print "in DESTROY\n" }

package main;

my $terminate = 0;

$SIG{INT} = \&sigint;

sub sigint { $terminate = 1; }

my $t = new Test;

while (1) {
    last if $terminate;
    sleep 10;
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文