我的示例代码:
#!/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
没有被困住,并且 testtrap.sh
没有被它们杀死。怎么了?
来自 https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html :
当 shell 等待实用程序执行前台命令完成时接收到已设置陷阱的信号时,与该信号关联的陷阱只有在前台命令完成后才会执行。
您的 shell 正在执行
sleep inf
。在 sleep inf
完成之前陷阱不会被执行。您仅将信号发送到 bash
进程,而不是 sleep
。