我有scriptA,它将执行另一个将在后台启动的脚本。现在我需要确保当我杀死scriptA(cmd + c)后,后台进程也被杀死了。
#!/bin/bash
echo "This script is about to run another script."
sh ../processes/processb/bin/startserver.sh &
FOO_PID=$!
echo "This script has just run another script." $FOO_PID
此脚本执行正常,但是一旦我按下cmd + c并对FOO_PID值执行'ps'命令,该过程仍然存在。我做错了什么?
UPDATE -----------
所以我尝试了下面的代码,但是仍然没有脚本C的进程被杀死。我认为它只是在按下ctrl + c时才终止scriptA(父),因此trap命令没有被执行?
#!/bin/bash
echo "This script is about to run another script."
../common/samples/bin/scriptC.sh &
mypid=$!
kill -0 "$mypid" && echo "My process is still alive."
echo "This script has just run another script." $mypid
trap "kill $mypid && kill $$" INT
答案 0 :(得分:3)
为trap
添加SIGINT
:
trap "kill $FOO_PID && kill $$" INT
或任何类型的退出,处理伪信号EXIT
:
trap "kill $FOO_PID && kill $$" EXIT