Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

SIGINT Handler

by nwboy74 (Novice)
on May 19, 2009 at 20:07 UTC ( #765017=perlquestion: print w/replies, xml ) Need Help??

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

    -- 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.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://765017]
Approved by Perlbotics
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2021-09-24 18:21 GMT
Find Nodes?
    Voting Booth?

    No recent polls found