Ubuntu
當系統要重新啟動時,程序可以獲得哪個信號(如 SIGINT 或 SIGTERM)?
我的應用程序需要在退出之前做一些事情,我已經通過處理信號處理了 ctrl-c 的情況
SIGINT
,但我也想處理系統要重新啟動的情況。我研究了一下,但發現
SIGTERM
是通過管理操作,系統在重新啟動之前不會發送SIGTERM
,是否正確?我可以處理任何其他信號嗎?
編輯:如果我的應用程序由 執行
systemd
,它是否使它更複雜或更容易處理?
發送的信號是可定制的,並記錄在
man systemd.kill
. 最有趣的部分是:KillSignal= Specifies which signal to use when stopping a service. This controls the signal that is sent as first step of shutting down a unit (see above), and is usually followed by SIGKILL (see above and below). For a list of valid signals, see signal(7). Defaults to SIGTERM. Note that, right after sending the signal specified in this setting, systemd will always send SIGCONT, to ensure that even suspended tasks can be terminated cleanly. FinalKillSignal= Specifies which signal to send to remaining processes after a timeout if SendSIGKILL= is enabled. The signal configured here should be one that is not typically caught and processed by services (SIGTERM is not suitable). Developers can find it useful to use this to generate a coredump to troubleshoot why a service did not terminate upon receiving the initial SIGTERM signal. This can be achieved by configuring LimitCORE= and setting FinalKillSignal= to either SIGQUIT or SIGABRT. Defaults to SIGKILL.
所以當你
systemctl stop *.service
,systemd 會SIGTERM
預設發送一個到服務中的主程序。如果程序沒有在TimeoutStopSec
(預設 90 秒)內退出,那麼systemd
將跟進一個SIGKILL
.當你在開發你的應用程序時,你不需要太考慮 init 系統。如果您不想對 的響應進行編碼
SIGTERM
,並且只想保留SIGINT
,則可以。您只需要確保您發布的任何 systemd 服務文件都包含KillSignal=SIGINT
.我沒有閱讀任何建議在重新啟動時
systemd
跳過KillSignal=
的內容。如果您在關閉時看到“Waiting for …”,那就是在systemd
等待響應KillSignal
。