[英]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.