⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch04_10.htm

📁 by Randal L. Schwartz and Tom Phoenix ISBN 0-596-00132-0 Third Edition, published July 2001. (See
💻 HTM
字号:
<html><head><title>Signals (Perl in a Nutshell, 2nd Edition)</title><link rel="stylesheet" type="text/css" href="../style/style1.css" /><meta name="DC.Creator" content="Stephen Spainhour" /><meta name="DC.Format" content="text/xml" scheme="MIME" /><meta name="DC.Language" content="en-US" /><meta name="DC.Publisher" content="O'Reilly &amp; Associates, Inc." /><meta name="DC.Source" scheme="ISBN" content="0596002416L" /><meta name="DC.Subject.Keyword" content="stuff" /><meta name="DC.Title" content="Perl in a Nutshell, 2nd Edition" /><meta name="DC.Type" content="Text.Monograph" /></head><body bgcolor="#ffffff"><img src="gifs/smbanner.gif" usemap="#banner-map" border="0" alt="Book Home" /><map name="banner-map"><area shape="rect" coords="1,-2,616,66" href="index.htm" alt="Java and XSLT" /><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map><div class="navbar"><table width="684" border="0"><tr><td align="left" valign="top" width="228"><a href="ch04_09.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0" /></a></td><td align="center" valign="top" width="228" /><td align="right" valign="top" width="228"><a href="ch04_11.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0" /></a></td></tr></table></div><h2 class="sect1">4.10. Signals</h2><p><a name="INDEX-785" /> <a name="INDEX-786" />Perl supports many facilities forInterprocess Communication (IPC), including signals and sockets.Regardless of which IPC form you use with Perl,you'll almost always tangle with signals.</p><p>Signals can be generated from any source, including key sequences onyour keyboard, an event on your system, or from a failed program.</p><p>For quite some time, Perl has used a simple signal handling module,in which <tt class="literal">%SIG</tt><a name="INDEX-787" /><a name="INDEX-788" /> was populated with keys thatrepresented the signal handlers your system supported.You'd invoke one of these handlers when Perl cameacross <tt class="literal">$SIG{'whatever_signal_here'}</tt>. In fact, evenin Perl 5.8, the <tt class="literal">%SIG</tt> interface is the same, butthe behavior of signals is entirely different. More on this shortly.</p><p>For signals to be useful, they must be trapped and dealt with.However, you shouldn't try to do too much when youtrap a signal. Generally, you should only generate a warning and dealwith the condition that caused the error. In a way,Perl's <tt class="literal">%SIG</tt> keeps you from doingtoo much. <tt class="literal">%SIG</tt> works like this:</p><blockquote><pre class="code">$SIG{I_GOT_THIS_SIGNAL} = \&amp;now_call_this_sub_to_handle_it;sub now_call_this_sub_to_handle it {    ...}</pre></blockquote><p>If you need to know which signals Perl is aware of, do a<tt class="literal">'kill -l'</tt> on a Unix system, or use<em class="emphasis">Config.pm</em>:</p><blockquote><pre class="code">#!/usr/local/bin/perl -wuse Config;print "Perl knows about the following signals:\n";print $Config{sig_name_init}, "\n";</pre></blockquote><p>Here's a simple snippet that lets you know ifsomeone sent you a <tt class="literal">HUP</tt> signal:</p><blockquote><pre class="code">$SIG{HUP} = \&amp;hic_hup;sub hic_hup {	my $signal = shift;	# Don't die for now.  Just warn us.	warn "Somebody sent me a SIG${signal}\n";}</pre></blockquote><p>Often, the type of signal you encounter in your Perl program willdictate how you should handle it. For example, you should assign<tt class="literal">'IGNORE'</tt> to the <tt class="literal">'CHLD'</tt> signalon many Unix platforms to reduce the possibility of creating zombieprocesses. Other signals, such as <tt class="literal">KILL</tt> and<tt class="literal">STOP</tt>, cannot and should not be ignored so easily.For this purpose, Perl lets you use a <tt class="literal">local()</tt><a name="INDEX-789" /> statement, which lets you temporarilyignore a signal:</p><blockquote><pre class="code">sub kill_handler {    local $SIG{KILL} = 'IGNORE'; # Inherited by all functions here    i_will_settle_for_denial();}sub i_will_settle_for_denial {	# KILL ignored for now.  Go in peace.}</pre></blockquote><p>Unix allows you to kill processes with negative process IDs bysending a <em class="firstterm">signal zero</em>. If you have a programthat starts itself and several children, use <tt class="literal">'kill-PARENT_PID'</tt> to kill the parent and all of the childrenprocesses. But obviously, if you send a <tt class="literal">HUP</tt> to theparent, you don't want the parent to die. You canavoid this with Perl and signals:</p><blockquote><pre class="code">sub be_nice_to_your_parents {	local($SIG{HUP}) = 'IGNORE';     kill('HUP', -$$);    # This pid and its kids}</pre></blockquote><p>Naturally, you don't have to do anything fancy withsignal handlers. You can simply die if the given<tt class="literal">$SIG{NAME}</tt> won't cause negativeeffects on your system if you mishandle it:</p><blockquote><pre class="code">$SIG{INT} = sub {    die "\nYou've interrupted me for one last time!\n"};</pre></blockquote><p>Keep in mind that it's not all fun and games withPerl and signals. If you don't know how yoursystem's C library and its signals implementationbehave, or if you haven't read the instructionsbefore firing your BB gun, you'll shoot your eyeout. We guarantee it!</p><p>As of Perl 5.8, you can probably be a little more confident inPerl's ability to handle even a bad system-specificsignals implementation. In the old days, when men were men andeyeless men were everywhere, a bad signals implementation at both asystem and Perl level, or a signal cropping up at the wrong time,could corrupt Perl's internal state. Thankfully,Perl 5.8 and later will postpone signal handling untilit's safe to proceed. This means that while thesignals interface doesn't change, even if yourprogram catches a signal at a specific place, Perl 5.8 and later willfinish whatever they are doing when the signal is encountered.</p><p>Finally, signals aren't limited to coping with thebehaviors of processes. You can also trap alarm signals for Perlfunctions and system calls alike if your Perl code lives in an<tt class="literal">eval( )</tt> block. For example, let'ssay you want to ping a host,<tt class="literal">your-host.your.domain</tt>, and you want the pingprocess to timeout in a reasonable amount of time if<tt class="literal">your-host.your.domain</tt> isn'tavailable. You can use <tt class="literal">alarm( )</tt> inside of<tt class="literal">eval( )</tt>, like so:</p><blockquote><pre class="code">#!/usr/local/bin/perl -wmy $to_ping = 'your-host.your.domain';my $a_secs = 5;eval {    local $SIG{ALRM} = sub { die "no dice for $to_ping" };    alarm $a_secs;    system("/usr/sbin/ping", $to_ping);    alarm 0;};if ($@ and $@ !~ /no dice for $to_ping/) { die }</pre></blockquote><p>Note that you may have to wait for the ping command itself totimeout. While <tt class="literal">alarm</tt> occurs after<tt class="literal">$a_secs</tt>, you won't see the"no dice for . . . " message until<tt class="literal">system( )</tt> (<tt class="literal">or qx( )</tt>) iscomplete. This is not the case for Perl functions such as<tt class="literal">flock( )</tt>, <tt class="literal">open( )</tt>,etc.<a name="INDEX-790" /><a name="INDEX-791" /></p><hr width="684" align="left" /><div class="navbar"><table width="684" border="0"><tr><td align="left" valign="top" width="228"><a href="ch04_09.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0" /></a></td><td align="center" valign="top" width="228"><a href="index.htm"><img src="../gifs/txthome.gif" alt="Home" border="0" /></a></td><td align="right" valign="top" width="228"><a href="ch04_11.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0" /></a></td></tr><tr><td align="left" valign="top" width="228">4.9. Filehandles</td><td align="center" valign="top" width="228"><a href="index/index.htm"><img src="../gifs/index.gif" alt="Book Index" border="0" /></a></td><td align="right" valign="top" width="228">4.11. Unicode</td></tr></table></div><hr width="684" align="left" /><img src="../gifs/navbar.gif" usemap="#library-map" border="0" alt="Library Navigation Links" /><p><p><font size="-1"><a href="copyrght.htm">Copyright &copy; 2002</a> O'Reilly &amp; Associates. All rights reserved.</font></p><map name="library-map"><area shape="rect" coords="1,0,85,94" href="../index.htm"><area shape="rect" coords="86,1,178,103" href="../lwp/index.htm"><area shape="rect" coords="180,0,265,103" href="../lperl/index.htm"><area shape="rect" coords="267,0,353,105" href="../perlnut/index.htm"><area shape="rect" coords="354,1,446,115" href="../prog/index.htm"><area shape="rect" coords="448,0,526,132" href="../tk/index.htm"><area shape="rect" coords="528,1,615,119" href="../cookbook/index.htm"><area shape="rect" coords="617,0,690,135" href="../pxml/index.htm"></map></body></html>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -