文章摘要
这篇文章介绍了如何在Command Line Interface(CLI)中使用Bash脚本实现对后台进程的终止控制。具体而言,脚本通过定义一个名为`onCtrlC`的函数来捕获`Ctrl+C`信号(即键盘输入的终止)。当`Ctrl+C`被捕获时,函数会调用`kill -9`命令同时终止两个进程:`do_sth_pid`和`progress_pid`。这里的`do_sth`函数负责运行一个需要一定时间完成的任务,而`progress`函数则用于实时显示进度条。脚本还使用了进程副本(通过`&`操作符)和shell脚本的`wait`命令来确保所有进程完成后再终止。通过这种方式,脚本能够可靠地在`Ctrl+C`事件下终止所有后台进程。
#!/bin/bash
trap ‘onCtrlC’ INT
function onCtrlC () {
#捕获CTRL+C,当脚本被ctrl+c的形式终止时同时终止程序的后台进程
kill -9 ${do_sth_pid} ${progress_pid}
echo
echo ‘Ctrl+C is captured’
exit 1
}
do_sth() {
#运行的主程序
sleep 10
}
progress() {
#进度条程序
local main_pid=$1
local length=20
local ratio=1
while [ “$(ps -p ${main_pid} | wc -l)” -ne “1” ] ; do
mark=’>’
progress_bar= for i in $(seq 1 “${length}”); do
if [ “$i” -gt “${ratio}” ] ; then
mark=’-‘
fi
progress_bar=”${progress_bar}${mark}”
done
printf “Progress: ${progress_bar}\r”
ratio=$((ratio+1))
#ratio=`expr ${ratio} + 1`
if [ “${ratio}” -gt “${length}” ] ; then
ratio=1
fi
sleep 0.1
done
}
do_sth &
do_sth_pid=$(jobs -p | tail -1)
progress “${do_sth_pid}” &
progress_pid=$(jobs -p | tail -1)
wait “${do_sth_pid}”
printf “Progress: done \n”