SIGTERM 不终止脚本

SIGTERM does not terminate script

我正在尝试理解这个脚本:

#!/usr/bin/env sh

trap "pkill -f sleep" term

sleep 1000

在 运行 脚本之后,我想通过发送 SIGTERM:

来停止它
# run script in the background
$ ./signals.sh &
[1] 5389

# check if script is running
$ ps aux | grep 'signals.sh\|sleep' | grep -v grep
sergioro  5389  0.0  0.0 216520  3112 pts/0    S    09:07   0:00 sh ./signals.sh
sergioro  5390  0.0  0.0 214984   708 pts/0    S    09:07   0:00 sleep 1000

# send SIGTERM to script
$ pkill -fe signals.sh
sh killed (pid 5389)

# why hasn't the script stopped after receiving SIGTERM?
$ ps aux | grep 'signals.sh\|sleep' | grep -v grep
sergioro  5389  0.0  0.0 216520  3112 pts/0    S    09:07   0:00 sh ./signals.sh
sergioro  5390  0.0  0.0 214984   708 pts/0    S    09:07   0:00 sleep 1000

# send SIGTERM to `sleep` command
$ pkill -fe sleep
sleep killed (pid 5390)
Terminated

# script has stopped
$ ps aux | grep 'signals.sh\|sleep' | grep -v grep

我的问题是如何通过将 SIGTERM 发送到脚本本身而不是 sleep 命令来停止脚本?为什么脚本中的 trap 没有终止睡眠命令?

只有在 sleep 完成后,shell 才能处理 trap

这可以达到你的预期:

#!/usr/bin/env sh

trap "pkill -f sleep" term

sleep 1000 & wait

参见手册页的 SIGNALS 部分,尤其是最后一段:

If bash is waiting for a command to complete and receives a signal for which a trap has been set, the trap will not be executed until the command completes. When bash is waiting for an asynchronous command via the wait builtin, the reception of a signal for which a trap has been set will cause the wait builtin to return immediately with an exit status greater than 128, immediately after which the trap is executed.