course:nctu-高等unix程式設計:chapter8
*Signals
0x00 Outline
- Introduction
- The signal function
- Interrupted system calls
- Reentrant functions
- Reliable signal model
- Functions for handling signals
- Other issues
0x01 Introduction
introduction
- Signals 是一個 software interrupts, 提供了處理 asynchronous events 的方式,一般城市皆須處理 signal 的問題
- 在原本的 signal model 中,signal 是不可靠的,不保證會收到,可能遺失。對 process 而言也難以關閉特定 signal
- 現今則多採用 reliable signal model,本章節也易此為主來討論
signal concepts
- 每個 signal 都有名稱,以
SIG
開頭,而 signal name 也皆在 header file 中被定義為正整數- <sys/signal.h>: FreeBSD 8.0 and Mac OS X 10.6.8
- <bits/signum.h>: Linux 3.2.0
- <sys/iso/signal_iso.h>: Solaris 10
- 幾個產生 signal 的情況
- The terminal-generated signals: 當 user 按下 Ctrl-C, Ctrl-BackSpace,Ctrl-Z 時
- Hardware exceptions: 發生除以零錯誤時
- Software conditions: SIGPIPE,SIGALRM
- The kill(2) function: 允許一個 process 發送任何 signal 給其他我們自己的或是有權限的 process 或 process group
- The kill(1) command: 允許 user 發送訊號給其他 processes
- 處理 signals (signal dispositions)
- Ignore the signal: 大多數 signal 可以忽略處理,但 SIGKILL 和 SIGSTOP signal 不能忽略
- Catch the signal: 我們可以註冊自己客製的 signal handler,但無法針對 SIGKILL 和 SIGSTOP 兩個 signal
- Let the default action apply: 每個 signal 都有預設的處理方式
0x02 The signal function
signal function
#include <signal.h> void (*signal(int signo, void (*func)(int)))(int); /* Returns: previous disposition of signal (see following) if OK, SIG_ERR on error */
- signo 是 signal name 或 signal number
- func 是當 signal 發生時要呼叫的 function(signal handler)
- func 也可以使用 SIG_IGN (忽略 signal) 或 SIG_DFL (預設行為處理)
- 因為不同系統對 signal 的實作不同,建議使用
sigaction
代替
signal setup
- 當程式啟動後,signal 一般是預設行為或是忽略
- 當 process 呼叫 fork 時,child 會繼承 parent 對 signal 的處理方式(signal dispositions)
- 當 process 呼叫 exec 時,exec 會將所有 signal 都設回 default action
- shell 會自動將 background process 的 SIGINT 和 SIGQUIT signal 設為 ignore
0x03 Interrupted system calls
course/nctu-高等unix程式設計/chapter8.txt · 上一次變更: 由 127.0.0.1