我正在尝试设置一个启动脚本,在该脚本中可以向该脚本已启动的进程发送“启动”和“停止”命令。
我想出的办法可以杀死该进程,但是我认为较大的进程会遇到麻烦,而且我认为可能会有更好的方法:
pingcheck()
{
ping -c2 "$1" &>/dev/null
return "$?"
}
start()
{
while :
do
if ! pingcheck "$our_ip"; then
echo "$our_ip NOT online, WANTEDID >> $WANTEDID"
else
echo "$our_ip IS online, WANTEDID >> $WANTEDID"
fi
done
}
stop()
{
#Find the start process's id
WANTEDID=$(ps aux | grep '[n]etworking.sh start' | awk '{print $2}' | head -n 1)
#Kill it in a new processgroup
setsid kill -9 "$WANTEDID"
exit 0
}
trap "stop" SIGINT SIGTERM
case "$1" in
start | stop ) "$1" ;;
esac
bash networking.sh start
192.168.20.5 IS online, WANTEDID >>
192.168.20.5 IS online, WANTEDID >>
192.168.20.5 IS online, WANTEDID >>
192.168.20.5 IS online, WANTEDID >>
192.168.20.5 IS online, WANTEDID >>
bash networking.sh stop
Killed
对于如何更好地编写此代码,我将不胜感激。
当我使用SIGTERM而不是-9时,我会在屏幕上看到它,bash崩溃(在ubuntu上:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ WANTEDID=26581
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ setsid kill -SIGTERM 26581
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ stop
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ps aux
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ awk '{print $2}'
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ grep '[n]etworking.sh start'
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ head -n 1
^C+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ WANTEDID=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ setsid kill -SIGTERM ''
kill: failed to parse argument: ''
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ exit 0
答案 0 :(得分:0)
感谢我在这里提供的所有出色建议(@ Aaron,@ Kamil Cuk),脚本现在看起来像这样:
pingcheck()
{
ping -c2 "$1" &>/dev/null
return "$?"
}
start()
{
while :
do
if ! pingcheck "$our_ip"; then
...do something...
sleep 10s
fi
done
}
stop()
{
pkill -nf "$0 start"
exit 0
}
case "$1" in
start | stop ) "$1" ;;
esac
它工作正常。 再次感谢大家!我非常感谢所有帮助。