在bash,$!是最後一個啟動過程的PID,是以沿着這條線的圖案應該有效:
mycommand &
last_pid=$!
sleep( $RANDOM )
kill -KILL $last_pid
當然,你可以改變你發送的信号,$RANDOM和你想睡覺的時間等之間的關系.
除非a)睡眠時間很長或b)你的機器啟動了很多短暫的過程,否則新程序獲得相同的PID的可能性不大.在Linux上,PID周期性地配置設定,最大值為32,765,是以,粗略地說,您必須在睡眠時間内啟動許多程序才有可能觸及屬于不同程序的相同PID.如果這是一個風險,你可以添加一個測試(從技術上講,這裡有一場比賽,但這不太可能是一個問題).以下似乎會做你想要的.
signal=KILL
sleep_a_while () {
sleep $[ ( $RANDOM % 150 ) + 60 ]m
}
while true; do
# Note: command launched in background:
/path/to/applicationfile -s 111.222.333.444 -u username -p password &
# Save PID of command just launched:
last_pid=$!
# Sleep for a while:
sleep_a_while
# See if the command is still running, and kill it and sleep more if it is:
if ps -p $last_pid -o comm= | grep -qs '^applicationfile$'; then
kill -$signal $last_pid 2> /dev/null
sleep_a_while
fi
# Go back to the beginning and launch the command again
done
我用一個等效的循環替換了自我執行.
在kill行上,由于競争,stderr重定向到/ dev / null是可取的.該過程可能會在ps完成的時間和執行kill的時間之間自然退出,進而産生無害的錯誤消息.除非PID存在的測試和信号的發送是一緻的,否則這種競争是不可避免的(并且無害).
如果打算一次最多運作一個applicationfile執行個體,則可以通過替換以下内容來完全避免此競争:
# See if the command is still running, and kill it and sleep more if it is:
if ps -p $last_pid -o comm= | grep -qs '^applicationfile$'; then
kill -$signal $last_pid 2> /dev/null
sleep_a_while
fi
附:
killall -q applicationfile && sleep_a_while
如果不能使用,Keith Reynolds的測試變體更好,因為它避免了不必要的grep,即使用:
# See if the command is still running, and kill it and sleep more if it is:
if [ "$(ps -p $last_pid -o comm=)" = "applicationfile" ]; then
kill -$signal $last_pid 2> /dev/null
sleep_a_while
fi