开发者

Why is object destructor not called when script terminates?

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 call开发者_JAVA百科ed 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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜