gpt4 book ai didi

linux - 通过结束进程来停止 bash 脚本的最佳方法

转载 作者:太空宇宙 更新时间:2023-11-04 12:01:45 25 4
gpt4 key购买 nike

我正在尝试设置一个启动脚本,我可以在其中向脚本已启动的进程发送“启动”和“停止”命令。

我想出的方法可以很好地杀死进程,但我认为对于更大的进程我会遇到麻烦,而且我也认为可能有更好的方法来做到这一点:

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
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++停止
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ps辅助
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ awk '{print $2}'
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ grep '[n]etworking.sh 开始'
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 头-n 1
^C+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ WANTEDID=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ setsid kill -SIGTERM ''
杀死:无法解析参数:''
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++退出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

而且效果很好。再次感谢大家!我非常感谢所有的帮助。

关于linux - 通过结束进程来停止 bash 脚本的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52150273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com