How to track and later kill a process in a script

Hello,

I am trying to write a script that turns off the screensaver for a certain period of time, then come back on. I have had it up and running for a while, but then I decided to refactor it a bit for my family members that are less computer savvy.

I am starting a subshell for the "meat" of the off script

(sleep $STIME ; sson ;exit) &

I want to be able to find this sleep command and kill the command. This allows the finishing of the script calling my sson script and then exiting.

I could always do a "ps ux|grep sleep|awk '{print $2}'|xargs kill", but if I happen to any other script with a sleep running that is not associated with sleeping the screesaver, this will kill that one too.

I was hoping to use the $! ability of bash on the subshell and kill that, but is many of you probably already knew, killing the bash doesn't kill the sleep. As I'm typing this, I thought of this:

(
sleep $STIME &
PID=$!
if [ ! -f /tmp/sleep.pid ] ; then
    touch /tmp/sleep.pid
else
    echo $PID >> /tmp/sleep.pid
fi
wait $PID
sson
exit
) &

I do the whole touch and append thing because I would like to keep a log of the pids and kill any that might have been run (or kill all previous before) in case my ssoff script is invoked twice.

Plus, I just want to do an exercise for my own learning on PID tracking.

Is this the way it should be done, or is there a better way of coding it?

With thanks,
Narnie

You can kill a process inside a script by using $! variable.
The use of $! variable is containing the process id of the last background process.

Here,is my simple script which tracks the background process in the script and kills it.

sleep 100 &
echo "Background Process ID:$!"
kill -9 $!

If you'll notice, that is the variable that I assigned to PID. I was just wondering if there might be a better way to do this. Also, it will be another script that would be canceling the process, hence my logging of it. My sson (screen saver on) script will be modified to kill all "ssoff" processes in case my family has more than one running. Or, I might add it as a feature of the ssoff script (or both).

My script example worked, just wondering if there were a better way to script it.

Consider the pstree command - you want the PPID for the process that is running your script name.

Nice, never knew of that command.

Thanks.

Loving to learn,
Narnie

---------- Post updated at 10:49 PM ---------- Previous update was at 10:34 PM ----------

Cool, so if I wanted to use my original script, I could do this:

woodnt@toshiba-laptop ~ $ pstree -p 20855| sed  's/.*sleep(\([0-9][0-9]*\))/\1/'
20856

and just modify that for my script. That is very nice.

Thanks for the learning op

Narnie