是否可以在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
您只需执行以下操作:
来自
man bash
关于trap
内置:查看:
有了这个适当的解决方案,无论是否退出,该功能都将被执行。