您的位置:首页 > 其它

[Perl] 常见signals解析

2016-04-24 23:12 295 查看

介绍

系统实现 中断机制 依赖于Signals,而其存在是为了当一个程序(Process)运行时,响应“用户请求” or 系统强制介入。

Signals are software interrupts sent to a program to indicate that an important event has occurred. The events can vary from user requests to illegal memory access errors. Some signals, such as the interrupt signal, indicate that a user has asked the program to do something that is not in the usual flow of control.

以下为常见的Signals,更多的可以尝试
kill -l
查看。总共64个(0 预留,所以0 - 64 占据 7 bits)

Note: 以下 Examples 实现使用 Perl5

Signal NameSignal NumberDescriptionExamples
SIGHUP1Hang up detected on controlling terminal or death of controlling process$SIG{HUP}
SIGINT2Issued if the user sends an interrupt signal (Ctrl + C).$SIG{INT}
SIGQUIT3Issued if the user sends a quit signal (Ctrl + D).TBD
SIGFPE8Issued if an illegal mathematical operation is attemptedTBD
SIGKILL9If a process gets this signal it must quit immediately and will not perform any clean-up operations. This signal cannot be handled (caught), ignored or blocked – rough terminationTBD
SIGALRM14Alarm Clock signal (used for timers)$SIG{ALRM}
SIGTERM15Software termination signal immediately (sent by kill by default). This is used for graceful termination of a process, unlike SIGKILL, it’s a graceful terminationTBD

|SIGCHLD | 17 | Child process exit signal, sent to parent process | $SIG{CHLD} |

赋值%SIG

大多数的Signals是用来被捕获并作出回应(无论是由用户or系统), 赋值可以为 
IGNORE
,
DEFAULT
and
\&SOMESUB
,依次列举如下:

$SIG{XXX} = ‘IGNORE’;

字面意思:忽略它,即使catch a signal也当没发生。例如
$SIG{CHLD}
,parent process 在catch a SIGCHLD后通常会回收该Child process资源。好吧,现在它不管了。还好OS提供backup。这是最省事的回收方式,常见REAPER

$SIG{XXX} = ‘DEFAULT’;

每种signal 都有 default action,即程序(Process) catch后应有的动作,可能如下:

Terminate the process.

Ignore the signal.

Dump core. This creates a file called core containing the memory image of the process when it received the signal.

Stop the process.

Continue a stopped process.

$SIG{XXX} = ‘\&SOMESUB’;

此处
\&SOMESUB
就是用户对该SIGXXX作出的回应,定义在
sub SOMESUB{# what shold do}
, 实例常见上文任意Examples

PS: %SIG 为Perl预定义的supervar,存储着所有Signals,遵循POSIX,常见perlvars

总结

每种Signals都有自身的特殊含义,虽然只用一个数字精简的表示, 就像汽车鸣笛, 当行人听见, 意味着等待或避让; 但前车听见了, 意思可就多了, 如催促其别龟速了; 也可能好心提醒车胎爆了. 所以,只有日常使用中实践使用,才能认识其应用场景,后续将继续补充Examples
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: