我的示例代码:
#!/bin/bash
LOGFILE="/tmp/example.log"
cleanup_function() {
echo "Script interrupted by SIGINT, cleaning up..." >> $LOGFILE
exit 0
}
shutdown_function() {
echo "Script terminated by SIGTERM, shutting down..."
exit 0
}
# Traps to handle SIGINT and SIGTERM
trap 'cleanup_function' SIGINT
trap 'shutdown_function' SIGTERM
echo "Script running. It waits for SIGINT or SIGTERM..." >> $LOGFILE
sleep inf
另存为testtrap.sh
在终端中:
$ ./testtrap.sh
在另一个终端中:
$ ps -A | grep testtrap.sh
28923 pts/2 00:00:00 testtrap.sh
$ kill -s SIGINT 28923
$ kill -s SIGTERM 28923
$ ps -A | grep testtrap.sh
28923 pts/2 00:00:00 testtrap.sh
SIGINT
并且SIGTERM
没有被困 etesttrap.sh
没有被他们杀死。怎么了?
来自https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html:
你的 shell 正在执行
sleep inf
。陷阱在完成之前不会被执行sleep inf
。您发送信号只是为了bash
处理,而不是为了sleep
。bash 手册中应该有类似的文档,并且还可以检查
man bash
.KamilCuk的答案是正确的:https://stackoverflow.com/a/78432970/1277576
该答案中链接的相同文档是这样说的:
因此,解决方案是替换
sleep inf
为:我做了一些测试,现在当脚本在前台运行时
./testtrap.sh
以及当我通过启动它在后台运行它时,陷阱都可以工作./testtrap.sh &
。