I have a script foo which, if provided an argument start, starts, among other things a script bar in the background and exits - bar contains an infinite loop.
At a later stage, I want to call foo with argument stop and I would like that script bar, which still runs in the background stops running.
What is the text book way of achieving this?
In case multiple bar instances can run simultaneously, and foo stop should stop/kill them all, use pkill:
$ pkill bar
to kill all processes named bar.
In case only one bar instance is allowed to run, a solution with a "pidfile" would be viable.
In foo:
pidfile=/var/run/bar.pid
if ((start)); then
if [ -e "$pidfile" ]; then
echo "$pidfile exists."
# clean-up, or simply abort...
exit 1
fi
bar &
echo $! >"$pidfile"
fi
if ((stop)); then
if [ ! -e "$pidfile" ]; then
echo "$pidfile not found."
exit 1
fi
kill "$(<"$pidfile")"
rm -f "$pidfile"
fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With