I have a shell script that starts a couple of background child processes. I want them to always be running - unless the parent process quits or gets killed (so I have the children in a loop that just always restarts if it quits).
This script seems to work relatively well, if I execute it directly. But as soon as I sudo
it, it will not clean up the other processes properly:
#!/bin/bash
trap "trap - SIGTERM && kill -- -$$" SIGINT SIGTERM EXIT
# Start first background thing
while true;
do
sleep 1
echo "SOME PROCESS RUNNING IN THE BACKGROUND"
echo "SHOULD AUTO-RESTART IF IT GETS KILLED OR CRASHES"
sleep 5
done &
# Start second background thing
while true;
do
sleep 3
echo "ANOTHER ONE..."
sleep 3
done &
# Wait for quit keypress
while true
do
echo "Press 'Q' to quit"
read -rsn1
if [ $REPLY == "q" ] || [ $REPLY == "Q" ]; then
echo "Are you sure? [Y/N]"
read -rsn1
if [ $REPLY == "y" ] || [ $REPLY == "Y" ]; then
kill -- -$$
exit
fi
fi
echo ""
sleep 1
done
# Wait
wait
When I'm sudo'ing, if I press CTRL+C, or press "Q" to quit, it will exit the parent (main) process but not the children and I receive this error:
adam@TG-BBCAM-01:~ $ sudo ./temp.sh
Press 'Q' to quit
Are you sure? [Y/N]
./temp.sh: line 31: kill: (-29098) - No such process
./temp.sh: line 1: kill: (-29098) - No such process
adam@TG-BBCAM-01:~ $ SOME PROCESS RUNNING IN THE BACKGROUND
SHOULD AUTO-RESTART IF IT GETS KILLED OR CRASHES
ANOTHER ONE...
SOME PROCESS RUNNING IN THE BACKGROUND
SHOULD AUTO-RESTART IF IT GETS KILLED OR CRASHES
ANOTHER ONE...
SOME PROCESS RUNNING IN THE BACKGROUND
SHOULD AUTO-RESTART IF IT GETS KILLED OR CRASHES
ANOTHER ONE...
SOME PROCESS RUNNING IN THE BACKGROUND
Obviously because it didn't kill the children, they're still running and flooding my shell still with output. When I don't sudo, it works great.
It seems to be the kill -- -$$
in both the trap and the "keypress monitor" part of my script. Commenting one out doesn't fix the other one.
Does anyone know how I can fix this? I would just like it to work in most any situation (well at least, sudo or not).
Thanks!