good chemistry is complicated, and a little bit messy -LW |
|
PerlMonks |
Re: Handling SIG INT multiple timesby sundialsvc4 (Abbot) |
on Oct 01, 2015 at 15:25 UTC ( [id://1143568]=note: print w/replies, xml ) | Need Help?? |
Basically (and this is true in any programming language ...) you must treat a signal like “the ringing of the telephone.” It is a signal that something needs to be done. Its main purpose in life is not “to wake you up,” but “to ensure that you are not asleep.” (That is to say, to avoid “busy waiting.”) It is usually not a good design to do substantial work within a signal handler, since that work will be done completely asynchronously to any other part of the application. (Signal handlers do not execute concurrently with themselves, as you saw, and if a signal is presented while the handler is still running, the additional signal(s) is usually dropped.) If the activity that is started by the signal is long-running, interrupts could happen again at any time. Therefore, the signal handler should not drive that activity. The actual handler should set a flag and get the hell out of there. Packages such as POE go a long way toward providing a comprehensive architecture out-of-the-box, but you can also do simpler things. Most likely, you will want to use a thread to execute the long process (what is now in your signal handler). When a signal arrives, the signal handler sets a boolean flag to True and strobes a condition-variable. The main loop of the thread then looks like this:
The thread will first await to be awakened. Then, it will loop and remain awake until the flag remains false, which means that another signal did not arrive in the meantime. It will then wait on the condition-variable again ... which quite probably has already been tripped again. Thus, as indicated, the meat-and-potatoes work of the thread might at any point find that there is nothing to do. The thread will not “stall,” but it might make a few extra do-nothing cycles, and who-cares. It is easy to see how this can be extended to handle orderly thread termination and wind-up of its affairs: a “please die” flag is set and the condition is strobed to be sure the thread is awake. In this explanation, I am not “getting specific to Perl,” and I will leave it to other Monks to write the code for you. ;-) These principles are generally true for any programming environment that supports true, pre-emptive threading.
In Section
Seekers of Perl Wisdom
|
|