[英]How does one correctly kill processes in bash
我使用以下脚本按超时终止进程:
# $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
kill $PID $($PID+1)
类的东西来kill $PID
重要的东西
编辑: $1
可能有一些麻烦,例如./bzip2 -ds sample3.bz2 -k
我刚刚开始使用此功能编写脚本。 我打算将其称为“超时”,但是在打开空白文件之前,我检查了是否已经有一个同名命令。 有...
编辑
如果您特别需要“ 1”作为失败时的返回值...
timeout 1 nano -w; `if [[ $? == 124 ]] ; then exit 1 ; fi ; exit $?`
平原怎么了
( eval "$1" ) &
sleep 300
kill %1
您将eval
作为后台程序,而不是它运行的命令,并且eval
是内置的shell,因此您要派生一个新的shell。 这就是为什么(我认为) $!
是当前外壳的PID。
一种简单的解决方案是避免使用eval
(为此以及通常的安全性问题)。
$1 "$@" &
PID=$!
的确,这不允许您将任意bash
命令行(管道,&&列表等)传递给脚本,但是您的用例可能不需要支持这种概括。 您通常会传递什么命令?
另外,这是对代码的一些重构,也许您会从中学习到一些东西:
#launch program and remember PID
eval "$1" &
PID=$!
echo "Program '$1' started, PID=$PID" # you can safely use single quotes inside double quotes, your variables are going to work in " " as well!
i=1
while (( i <= 300 )) # use (( )) for math operations!
do
ps -p "$PID" >> /dev/null # it is a good rule to quote every variable, even if you're pretty sure that it doesn't contain spaces
if [[ $? != 0 ]]; then # Try to use [[ ]] instead of [. It is modern bash syntax
wait "$PID"
exit "$?" #success, return rc of program
fi
((i++))
echo "waiting 1 second..."
sleep 1
done
#program does not want to exit itself, kill it
echo "killing program..."
kill "$PID"
exit 1 #failed
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.