slm..
37
PROCESS_NUM使用这种单线程,您几乎可以完成所有任务:
[ `pgrep $1` ] && return 1 || return 0
如果你正在寻找一个部分匹配,即程序被命名为foobar,你希望你$1只是foo,你可以添加-f switch到pgrep:
[[ `pgrep -f $1` ]] && return 1 || return 0
把它们放在一起你的脚本可以像这样重做:
#!/bin/bash
check_process() {
echo "$ts: checking $1"
[ "$1" = "" ] && return 0
[ `pgrep -n $1` ] && return 1 || return 0
}
while [ 1 ]; do
# timestamp
ts=`date +%T`
echo "$ts: begin checking..."
check_process "dropbox"
[ $? -eq 0 ] && echo "$ts: not running, restarting..." && `dropbox start -i > /dev/null`
sleep 5
done
运行它看起来像这样:
# SHELL #1
22:07:26: begin checking...
22:07:26: checking dropbox
22:07:31: begin checking...
22:07:31: checking dropbox
# SHELL #2
$ dropbox stop
Dropbox daemon stopped.
# SHELL #1
22:07:36: begin checking...
22:07:36: checking dropbox
22:07:36: not running, restarting...
22:07:42: begin checking...
22:07:42: checking dropbox
希望这可以帮助!