Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

How do I trap control characters/signals?

by faq_monk (Initiate)
on Oct 08, 1999 at 00:29 UTC ( [id://718]=perlfaq nodetype: print w/replies, xml ) Need Help??

Current Perl documentation can be found at perldoc.perl.org.

Here is our local, out-dated (pre-5.6) version:

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 Signals and chapter 6 of the Camel.

Be warned that very few C libraries are re-entrant. Therefore, if you attempt to print() 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 syswrite() instead of print().

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 malloc() is not called (eg, by setting a variable that already has a value).

For example:

    $Interrupted = 0;   # to ensure it has a value
    $SIG{INT} = sub {
        $Interrupted++;
        syswrite(STDERR, "ouch
", 5);
    }

However, because syscalls restart by default, you'll find that if you're in a ``slow'' call, such as <FH>, read(), connect(), or wait(), 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 flock() in Signals or chapter 6 of the Camel.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2024-04-18 10:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found