in reply to Re^2: Have $SIG{INT} ask if user wants to quit
in thread Have $SIG{INT} ask if user wants to quit

First you should make sure you are very familiar with Signals. Then you need to carefully consider the quirks of your platform(s). There are many, sometimes subtle and sometimes critical differences between the various operating systems.

There are two possibilities that will generally be "safe": the first is to do nothing but set a flag in your interrupt handler and take the appropriate action elsewhere; the other is to die in your signal handler and, where appropriate, run code in an eval to handle the abnormal termination, as in the example I showed previously. Doing anything else in the signal handler tends to be problematic and tricky, as you are finding out.

If your main program consists of a tight loop with rapid iterations, the first approach can work well. Just add a test for the flag in the main loop and it will be tested reasonably soon after the signal is caught.

If you have some long running sections of code in which it is inconvenient to scatter checks for a flag and you want a prompt response to ^C then the second approach is probably necessary. It allows you to terminate long running sections without explicit coding within the section.

If the main problem is interrupts while prompting for interactive input, as in your example, then I suggest creating a subroutine to prompt and collect the response with the subroutine implemented similarly to my previous example. While it may be tedious to revise your program if there are many instances, it will be quite straight forward and will not require significant change to the structure.

Otherwise, you can investigate ways to restore the I/O layers (which may differ depending on platform and perl compile and run-time options) to a functional state after doing I/O in the signal handler. I don't know enough about the I/O implementations to do anything other than steer clear of I/O in signal handlers myself. Sorry...

If you can post representative samples of your actual code, you may get some further helpful suggestions.

  • Comment on Re^3: Have $SIG{INT} ask if user wants to quit