在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