在 bash 脚本中检查并终止挂起的后台进程
Checking and killing hanged background processes in a bash script
假设我在 bash
中有这个伪代码
#!/bin/bash
things
for i in {1..3}
do
nohup someScript[i] &
done
wait
for i in {4..6}
do
nohup someScript[i] &
done
wait
otherThings
然后说这个 someScript[i] 有时会挂起。
有没有办法获取进程 ID(使用 $!)
并定期检查该进程是否花费了超过指定的时间,之后我想用 kill -9 杀死挂起的进程?
一种可能的方法:
#!/bin/bash
# things
mypids=()
for i in {1..3}; do
# launch the script with timeout (3600s)
timeout 3600 nohup someScript[i] &
mypids[i]=$! # store the PID
done
wait "${mypids[@]}"
不幸的是@Eugeniu 的回答对我不起作用,超时报错。
不过我发现执行此例程很有用,我将 post 放在这里,这样如果遇到我的相同问题,任何人都可以利用它。
创建另一个这样的脚本
#!/bin/bash
#monitor.sh
pid=
counter=10
while ps -p $pid > /dev/null
do
if [[ $counter -eq 0 ]] ; then
kill -9 $pid
#if it's still there then kill it
fi
counter=$((counter-1))
sleep 1
done
然后在主要工作中你只需输入
things
for i in {1..3}
do
nohup someScript[i] &
./monitor.sh $! &
done
wait
通过这种方式,对于您的任何 someScript,您将拥有一个并行进程,检查它是否在每个选定的时间间隔(直到计数器决定的最长时间)仍然存在,并且如果相关进程死亡(或获取),它实际上会自行退出杀)
假设我在 bash
中有这个伪代码#!/bin/bash
things
for i in {1..3}
do
nohup someScript[i] &
done
wait
for i in {4..6}
do
nohup someScript[i] &
done
wait
otherThings
然后说这个 someScript[i] 有时会挂起。
有没有办法获取进程 ID(使用 $!) 并定期检查该进程是否花费了超过指定的时间,之后我想用 kill -9 杀死挂起的进程?
一种可能的方法:
#!/bin/bash
# things
mypids=()
for i in {1..3}; do
# launch the script with timeout (3600s)
timeout 3600 nohup someScript[i] &
mypids[i]=$! # store the PID
done
wait "${mypids[@]}"
不幸的是@Eugeniu 的回答对我不起作用,超时报错。
不过我发现执行此例程很有用,我将 post 放在这里,这样如果遇到我的相同问题,任何人都可以利用它。
创建另一个这样的脚本
#!/bin/bash
#monitor.sh
pid=
counter=10
while ps -p $pid > /dev/null
do
if [[ $counter -eq 0 ]] ; then
kill -9 $pid
#if it's still there then kill it
fi
counter=$((counter-1))
sleep 1
done
然后在主要工作中你只需输入
things
for i in {1..3}
do
nohup someScript[i] &
./monitor.sh $! &
done
wait
通过这种方式,对于您的任何 someScript,您将拥有一个并行进程,检查它是否在每个选定的时间间隔(直到计数器决定的最长时间)仍然存在,并且如果相关进程死亡(或获取),它实际上会自行退出杀)