在bash脚本中检查并终止被挂起的后台进程

时间:2015-06-24 12:15:13

标签: bash process wait kill pid

说我在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

并说这个某些剧本[i]有时最终会挂起来。

有没有办法可以获取进程ID(使用$!) 并定期检查进程是否花费超过指定的时间,之后我想用kill -9杀死被挂起的进程?

2 个答案:

答案 0 :(得分:1)

不幸的是@Eugeniu的答案对我不起作用,超时给出了错误。

但是我发现这个例程非常有用,我会在这里发布,所以任何人都可以利用它,如果遇到同样的问题。

创建另一个类似这样的脚本

#!/bin/bash
#monitor.sh

pid=$1

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,你将有一个并行进程,检查它是否仍然存在于每个选定的时间间隔(直到计数器决定的最大时间),如果相关进程死亡(或被杀死),它实际上会自行退出

答案 1 :(得分:0)

一种可能的方法:

#!/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[@]}"