常见系统Signals解析

介绍

系统实现 中断机制 依赖于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 Name Signal Number Description Examples
SIGHUP 1 Hang up detected on controlling terminal or death of controlling process $SIG{HUP}
SIGINT 2 Issued if the user sends an interrupt signal (Ctrl + C). $SIG{INT}
SIGQUIT 3 Issued if the user sends a quit signal (Ctrl + D). TBD
SIGFPE 8 Issued if an illegal mathematical operation is attempted TBD
SIGKILL 9 If 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 termination TBD
SIGALRM 14 Alarm Clock signal (used for timers) $SIG{ALRM}
SIGTERM 15 Software termination signal immediately (sent by kill by default). This is used for graceful termination of a process, unlike SIGKILL, it's a graceful termination TBD
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

你可能感兴趣的:(常见系统Signals解析)