Why is object destructor not called when script terminates?
Asked Answered
E

2

7

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?

Entozoic answered 13/4, 2010 at 11:19 Comment(0)
O
7

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

Oilcan answered 13/4, 2010 at 11:53 Comment(0)
I
6

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.

Isoleucine answered 13/4, 2010 at 11:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.