是否可以在shell脚本终止时调用一个函数?我有一些守护进程在后台运行,它们的进程ID存储在一个数组中。我希望在脚本终止时(无论出于何种原因)调用一个清理函数/处理程序来终止所有守护进程。
# want the below function to be called when the shell script terminates for whatsoever reason
purge () {
for pid in ${pids[@]}; do
kill -9 $pid
done
}
./daemon1 > a.txt 2>&1 & pids+=($!)
./daemon2 > b.txt 2>&1 & pids+=($!)
./daemon3 > c.txt 2>&1 & pids+=($!)
for pid in ${pids[@]}; do
echo "process: $pid"
done