我正在尝试创建一个 bash 脚本,该脚本将运行多个长期存在的脚本——所有脚本都将在脚本结束时终止。例如:
x.sh:
while :; do sleep 10 && echo '10 seconds passed'; done
Run Code Online (Sandbox Code Playgroud)
y.sh 的伪代码:
./x.sh [anchored&]
./x.sh [anchored&]
./x.sh [anchored&]
Run Code Online (Sandbox Code Playgroud)
然后在 shell 中,应该能够执行以下操作:
$ ./y.sh
# after 10 seconds
10 seconds passed
10 seconds passed
10 seconds passed
# after another 10 seconds
10 seconds passed
10 seconds passed
10 seconds passed
^[CTRL-C]
$ # all scripts are now canceled
Run Code Online (Sandbox Code Playgroud)
当然,在我的实际用例中,我不是多次运行相同的脚本 (x.sh),而是运行不同的命令。
这是您可以使用的快速解决方案。
#!/bin/bash
trap terminate SIGINT
terminate(){
pkill -SIGINT -P $$
exit
}
#the rest of your code goes here
./x.sh &
./x.sh &
wait
Run Code Online (Sandbox Code Playgroud)
trap按下terminate时将执行该功能CTRL-C。该函数将pkill在其父进程PID是PID发送信号的脚本的当前进程的所有进程上执行SIGINT。
将wait在脚本确保年底,该脚本保持,而儿童进程正在运行运行。