我想要優雅的如果有人中止我的 Jenkins 工作,它就會被終止,所以我嘗試捕獲中止信號並使用 shell 腳本自訂終止步驟。
但詹金斯似乎忽略了所有陷阱並強行殺死
要測試的範例腳本
exit_script() {
echo "Printing something special!"
echo "traped & killed " >>text.txt
echo "Maybe executing other commands!"
trap - INT TERM ABRT QUIT HUP # clear the trap
kill -- -$$ # Sends SIGTERM to child/sub processes
}
trap 'exit_script' INT KILL ABRT QUIT HUP
echo "pid is $$"
echo "pid is $$" > test.txt
count=0
sleep 10
echo 1
echo 1 >>test.txt
sleep 10
echo 2
echo 2 >>test.txt
sleep 10
echo 3
echo 3 >>test.txt
sleep 10
echo 4
echo 4 >>test.txt
sleep 10
echo 5
echo 5 >>test.txt
sleep 10
echo 6
echo 6 >>test.txt
exit 0
我正在尋找如何誘捕訊號術語在 jenkins 中發出信號並自訂終止命令。
僅供參考:這個腳本在我的系統 bash 中運作正常,只需要更改 INT->SIGINT 等。
答案1
我認為它工作正常,只是需要進行一些修正,如果與陷阱相關的功能有任何問題,即exit_script()
它將無法工作。
我通過刪除對其進行了測試kill -- -$$
,它工作正常,正在調用該函數並且該過程繼續執行。
答案2
一般來說,在 shell 腳本中,您可以透過以下方式擷取 SIGTERM 訊號
trap 'exit_script' TERM
PS 捕捉 KILL 不起作用,列出 QUIT 兩次也沒有幫助。