FAQ 8.13 How do I trap control characters/signals?


P

PerlFAQ Server

This is an excerpt from the latest version perlfaq8.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

--------------------------------------------------------------------

8.13: How do I trap control characters/signals?

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" in perlipc and the section on "Signals" in
the Camel.

You can set the values of the %SIG hash to be the functions you want to
handle the signal. After perl catches the signal, it looks in %SIG for a
key with the same name as the signal, then calls the subroutine value
for that key.

# as an anonymous subroutine

$SIG{INT} = sub { syswrite(STDERR, "ouch\n", 5 ) };

# or a reference to a function

$SIG{INT} = \&ouch;

# or the name of the function as a string

$SIG{INT} = "ouch";

Perl versions before 5.8 had in its C source code signal handlers which
would catch the signal and possibly run a Perl function that you had set
in %SIG. This violated the rules of signal handling at that level
causing perl to dump core. Since version 5.8.0, perl looks at %SIG after
the signal has been caught, rather than while it is being caught.
Previous versions of this answer were incorrect.



--------------------------------------------------------------------

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in
perlfaq.pod.
 
Ad

Advertisements


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top