nwboy74 has asked for the wisdom of the Perl Monks concerning the following question:

I'd like to implement a SIGINT handler to save a file in the event that it receives an interrupt. Unfortunately, as soon as I override $SIG{INT}, my interrupt (ctrl-c) is delayed until the current operation is complete. I have a program that needs to be dormant until a given day of the week. I thought I'd just have the program sleep for a day and when it wakes up, check the date. It is running in Windows. Waiting a day for the signal to be processed is no good. Without the save feature:
while (1) { # get the date if ((localtime)[6] eq 4) { # do processing ... } else { sleep 86400; } }
After a ctrl-c is issued, the program immediately terminates. If I try to get some kind of shutdown hook implemented like below...
my $interrupted = 0; $SIG{INT} = sub { $interrupted = 1; &save_file; die; }; while (!$interrupted) { # get the date if ((localtime)[6] eq 4) { # do processing ... } else { sleep 86400; } }
... the signal doesn't get acted upon until the sleep statement finishes. Or perhaps there is a better way to do this.

Replies are listed 'Best First'.
Re: SIGINT Handler
by revdiablo (Prior) on May 19, 2009 at 20:39 UTC

    There are a couple options. I've listed them in my order of my personal preference.

    1. Use Windows Task Scheduler instead
    2. Sleep for shorter period of time (implement a more intelligent scheduling algorithm)
    3. Disable safe signal handling. From perlipc:
      If you want the old signal behaviour back regardless of possible memory corruption, set the environment variable PERL_SIGNALS to "unsafe" (a new feature since Perl 5.8.1).
Re: SIGINT Handler
by targetsmart (Curate) on May 20, 2009 at 05:45 UTC
    see Do's and Dont's inside a signal handler

    Vivek
    -- In accordance with the prarabdha of each, the One whose function it is to ordain makes each to act. What will not happen will never happen, whatever effort one may put forth. And what will happen will not fail to happen, however much one may seek to prevent it. This is certain. The part of wisdom therefore is to stay quiet.