perlfaq nodetype
faq_monk
<P>
You don't actually ``trap'' a control character. Instead, that character
generates a signal which is sent to your terminal's currently foregrounded
process group, which you then trap in your process. Signals are documented
in [perlman:perlipc|Signals] and chapter 6 of the Camel.
<P>
Be warned that very few
<FONT SIZE=-1>C</FONT> libraries are re-entrant. Therefore, if you attempt to
<CODE>print()</CODE> in a handler that got invoked during another stdio operation your internal structures will likely be in an inconsistent state, and your program will dump core. You can sometimes avoid this by using
<CODE>syswrite()</CODE> instead of
<CODE>print().</CODE>
<P>
Unless you're exceedingly careful, the only safe things to do inside a signal handler are: set a variable and exit. And in the first case, you should only set a variable in such a way that
<CODE>malloc()</CODE> is not called (eg, by setting a variable that already has a value).
<P>
For example:
<P>
<PRE> $Interrupted = 0; # to ensure it has a value
$SIG{INT} = sub {
$Interrupted++;
syswrite(STDERR, &quot;ouch
&quot;, 5);
}
</PRE>
<P>
However, because syscalls restart by default, you'll find that if you're in a ``slow'' call, such as
<FONT SIZE=-1>&lt;FH&gt;,</FONT>
<CODE>read(),</CODE>
<CODE>connect(),</CODE> or
<CODE>wait(),</CODE> that the only way to terminate them is by ``longjumping'' out; that is, by raising an exception. See the time-out handler for a blocking
<CODE>flock()</CODE> in
[perlman:perlipc|Signals] or chapter 6 of the Camel.
<P>