# Signals ![](https://i.imgur.com/ueqiVEZ.png) ![](https://i.imgur.com/B3wQe4d.png) ![](https://i.imgur.com/RTljqVR.png) ![](https://i.imgur.com/YrwKqwN.png) ![](https://i.imgur.com/ANw063D.png) ![](https://i.imgur.com/f63h2XK.png) ![](https://i.imgur.com/MM0m1XL.png) ![](https://i.imgur.com/P8s7DkQ.png) ![](https://i.imgur.com/8leDNXh.png) ![](https://i.imgur.com/PO4g9Vk.png) # Data Structures Associated with Signals ![](https://i.imgur.com/HVbzQ5S.png) ![](https://i.imgur.com/1YuzYGo.png) ![](https://i.imgur.com/2d8QHNR.png) Signal descriptor related to signal handling ![](https://i.imgur.com/whBq3OM.png) ![](https://i.imgur.com/m9P18kb.png) # The Role of Signals Linux系統各個processes會有不同的state,這些processes要嘛屬於user applications要嘛就屬於kernel.我們需要一種機制來協調他們的活動,其中一種辦法就是讓process可以在有重要的事情發生時去通知其他process. signal基本上是一種one way notification. * Kernel -> process * process -> other process * process -> 自己 不只hardware可以interrupt cpu, signals也可以interrupt process execution.(software interrupts) * hardware interrupt -> interrupt handlers * signal interrupt -> signal handlers 有些singals直接mapping到一些hot key * SIGINT -> ctrl+c * SIGSTOP -> ctrl+z * SIGQUIT -> ctrl+\ # How does a signal affect the state of a Linux process? ![](https://i.imgur.com/ovNFdwg.png) 有些signals會直接終結掉被通知到process * SIGHUP * SIGINT * SIGTERM * SIGKILL 有些signals終結掉process後會附送core dump讓人debug * SIGABRT -> abort signal * SIGBUS -> bus error * SIGILL -> illegal instruction * SIGSEGV -> invalid memory reference * SIGSYS -> bad system call 有些signals stop the process * SIGSTOP * SIGTSTP 有些signals resumes a stopped process * SIGCONT 你可以在program裡覆寫掉signal的行為 * SIGKILL and SIGSTOP除外 例子 ![](https://i.imgur.com/KWf3ved.png) # Aren't signals similar to exceptions? ![](https://i.imgur.com/rAWomr9.png) # Are Linux signals synchronous or asynchronous? 都可 * Synchronous(伴隨CPU內部指令的順序發生) * 當CPU執行到錯誤指令例如illegal addresss access的時候,signals會send給發生的thread.這也被稱為 traps,因為會觸發trap進kernel trap handler * Asynchronous(外部發生的,跟CPU內部指令順序無關) * 例如被其他process send SIGKILL,這也被稱為software interrupts # What's the typical lifecycle of a signal? ![](https://i.imgur.com/jr7Bhmm.png) System calls and functions that can generate signals * raise * kill * killpg * pthread_kill * sigqueue Delivery: * signal還沒被送達目標會是pending狀態 * 如果一個process目前是block signal狀態, signal會一直pending直到block解除 Processing: signal可以怎樣被處理? * 每個signal都有一個default動作 * ignore the signal * terminate the process * core dump * stop/continue * ....... * 對於non default的行為,可以call handler來處理--> sigaction function # blocking and unblocking signals Signals可能會interrupt一個正在執行重要任務的code,process這時可以選擇Blocking signals. * 每個procss都可以指定要block哪種signals * 如果被指定block的signals被送來了,kernel會先pending住,等unblock在送給你,這個block的動作叫做signal mask signal mask * 可以用sigprocmask -> singlethreaded * pthread_sigmask -> multi-threaded