in reply to Problem with alarm()
Otherwise, you're telling Perl to schedule an alarm() for ten seconds later, print the message and the cancel the alarm. Unless your machine is exceptionally slow, this would not work on *nix either because the print should take much less than 10 seconds, so the alarm gets cancelled.eval{ $SIG{ALRM} = sub {die "DING-DING"}; alarm(10); sleep(20); # <-- This line is missing print "I am frustrated."; alarm(0); };
As a side note, it is a very good idea to try to keep your signal handlers small and simple. Perl's instructions are quite complex in terms of the processing involved.
Signals (the result of an alarm, for example) can arrive at any point in time. In particular, they can arrive just in the middle of adding an entry to a hash. This has the potential to call your signal handler with a corrupt state in part of your program's data.
With recent versions of Perl, this is less of an issue but I thought in throwing this piece of advice just in case.
An alternative you can use, is what is sometimes called a post-file. Your expensive function can check periodically wether this file exists. If it does, it can abort itself gracefully. Just remember to remove the file when your program starts. The code to do this would be something along the lines of
You can refine this technique and create the file when you enter the long_running_function() and then check its age periodically until it reaches a threshold, at which you bail out.sub long_running_function { ... while ($your_condition) { ... return undef if -f $post_file; # Or die() if you want ... } } unlink $post_file; # May fail silently, but who cares? ... &long_running_function(); ...
Regards.
|
|---|