Reputation: 623
I am trying to setup a startup script where I can send "start" and "stop" commands to the processes that the script has started.
What I came up with kills the process(es) alright, but I think I will get in trouble for larger processes, and I also think there might be a better way of doing this:
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
I would be grateful for any advice on how to write this better.
When I use SIGTERM, instead of -9 I get this in the screen and bash crashes (On 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
Upvotes: 0
Views: 236
Reputation: 623
Thanks to all the stellar advice I got here (@Aaron, @Kamil Cuk), the script now looks like this:
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
And it works fine. Thanks again everyone! I deeply appreciate all the help.
Upvotes: 1