Perl信号处理学习简单小结
Unix下常见的处理信号
No Name DefaultAction Description 1 SIGHUP terminateprocess terminallinehangup 2 SIGINT terminateprocess interruptprogram 3 SIGQUIT createcoreimage quitprogram 4 SIGILL createcoreimage illegalinstruction 5 SIGTRAP createcoreimage tracetrap 6 SIGABRT createcoreimage abortprogram(formerlySIGIOT) 7 SIGEMT createcoreimage emulateinstructionexecuted 8 SIGFPE createcoreimage floating-pointexception 9 SIGKILL terminateprocess killprogram 10 SIGBUS createcoreimage buserror 11 SIGSEGV createcoreimage segmentationviolation 12 SIGSYS createcoreimage non-existentsystemcallinvoked 13 SIGPIPE terminateprocess writeonapipewithnoreader 14 SIGALRM terminateprocess real-timetimerexpired 15 SIGTERM terminateprocess softwareterminationsignal 16 SIGURG discardsignal urgentconditionpresentonsocket 17 SIGSTOP stopprocess stop(cannotbecaughtorignored) 18 SIGTSTP stopprocess stopsignalgeneratedfromkeyboard 19 SIGCONT discardsignal continueafterstop 20 SIGCHLD discardsignal childstatushaschanged 21 SIGTTIN stopprocess backgroundreadattemptedfromcontrolterminal 22 SIGTTOU stopprocess backgroundwriteattemptedtocontrolterminal 23 SIGIO discardsignal I/Oispossibleonadescriptor(seefcntl(2)) 24 SIGXCPU terminateprocess cputimelimitexceeded(seesetrlimit(2)) 25 SIGXFSZ terminateprocess filesizelimitexceeded(seesetrlimit(2)) 26 SIGVTALRM terminateprocess virtualtimealarm(seesetitimer(2)) 27 SIGPROF terminateprocess profilingtimeralarm(seesetitimer(2)) 28 SIGWINCH discardsignal Windowsizechange 29 SIGINFO discardsignal statusrequestfromkeyboard 30 SIGUSR1 terminateprocess Userdefinedsignal1 31 SIGUSR2 terminateprocess Userdefinedsignal2
perl的信号处理原理
Perl提供了%SIG这个特殊的默认HASH.调用需要使用到系统保留全局HASH数组%SIG,即使用'$SIG{信号名}'截取信号,相当于,在perl程序中出现这个信号时,执行我们自己定义某段代码(子函数)的地址值(定义信号响应函数),这代码就是截取这个信息后要执行的结果了.
举个SIGALRM例子,也就是超时处理:
my$timeout=10; eval{ local$SIG{ALRM}=sub{die"alarm\n"};#\nrequired alarm$timeout;#如果到了$timeout时间就会去执行上面的sub sleep15; print"iftimeout,thiswillnotprint"; alarm0;#恢复到默认的状态 }; if($@){ die unless$@eq"alarm\n"; #可能捕获的不是超时,是其他错误,就die吧 print"timeout\n"; } else{ print"nottimeout"; }
这里要说一下perl的错误捕获机制
eval{ open(FH,”domains.txt”)ordie“Can'topenfiles,$!”; };
捕获异常
if($@){#出现异常} else{#无异常,打印文件内容 while(){ … } closeFH; }
如果eval块中的程序有语法错误、运行时错误或者遇到die语句,eval将返回undef。错误码被保存在$@中。