【发布时间】:2013-08-23 11:17:04
【问题描述】:
我使用以下脚本通过超时杀死进程:
# $1 - name of program and its command line
#launch program and remember PID
eval "$1" &
PID=$!
echo "Program '"$1"' started, PID="$PID
i=1
while [ $i -le 300 ]
do
ps -p $PID >> /dev/null
if [ $? -ne 0 ]
then
wait $PID
exit $? #success, return rc of program
fi
i=$(($i+1))
echo "waiting 1 second..."
sleep 1
done
#program does not want to exit itself, kill it
echo "killing program..."
kill $PID
exit 1 #failed
到目前为止,它运行良好,但今天,我注意到 htop 中有一堆“挂起”进程,所以我检查了一下,结果发现,$PID 在这种情况下不是 ID程序进程,但脚本本身,我检查的所有时间,程序的 ID 是$PID+1。现在,问题是,我的假设是否正确,它将始终是 $PID+1,我不会通过将 kill $PID 替换为 kill $PID $($PID+1) 之类的东西来杀死重要的东西
编辑:$1 可能有几个要求,例如 ./bzip2 -ds sample3.bz2 -k
【问题讨论】:
-
不,PID 可以是任何值。这取决于系统上运行的内容。
-
您可以使用
pidof <progname>返回进程的pid。在这种情况下是pidof $1。 -
@SakthiKumar 这可能正是我需要的,谢谢,我会测试它并尽快回复
-
Inside a bash script, how to get PID from a program executed when using the eval command? 的可能副本。即,尝试
eval "$1 &"而不是eval "$1" &。