Watching a process

There are a few more topics that we should look at in this chapter. Suppose you want to be alerted when a running process ends on your system.

Here's a script that notifies the user when the specified process ends. Note that there are other ways to do this task, this is just one approach.

Chapter 3 - Script 12

#!/bin/sh
#
# 5/3/2017
#
echo "script12 - Linux Scripting Book"

if [ $# -ne 1 ] ; then
 echo "Usage: script12 process-directory"
 echo " For example: script12 /proc/20686"
 exit 255
fi

FN=$1                        # process directory i.e. /proc/20686
rc=1
while [ $rc -eq 1 ]
do
 if [ ! -d $FN ] ; then      # if directory is not there
  echo "Process $FN is not running or has been terminated."
  let rc=0
 else
  sleep 1
 fi
done

echo "End of script12"
exit 0

To see this script in action run the following commands:

  • In a terminal, run script9
  • In another terminal run ps auxw | grep script9. The output will be something like this:
    guest1   20686  0.0  0.0 106112  1260 pts/34   S+   17:20   0:00 /bin/sh ./script9
    guest1   23334  0.0  0.0 103316   864 pts/18   S+   17:24   0:00 grep script9
  • Use the process ID from script9 (in this case 20686) and use it as the parameter to run script12:
    $ script12 /proc/20686

You may let it run for a bit if you want. Eventually go back to the terminal that is running script9 and terminate it with Ctrl + C. You will see script12 output a message and then also terminate. Feel free to experiment with this one as it has a lot of important information in it.

You may notice that in this script I used a variable, rc, to determine when to end the loop. I could have used the break command as we saw earlier in this chapter. However, using a control variable (as it's often called) is considered to be a better programming style.

A script like this can be very useful when you have started a command and then it takes longer than you expected for it to finish.

For example, a while back I started a format operation on an external 1 TB USB drive using the mkfs command. It took a few days to complete and I wanted to know exactly when so that I could continue working with the drive.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.23.63.252