5

I want to create a service that monitors the existence of a certain process. I wrote the following shell script:

#!/bin/sh
while :
do
w=`ps u -A | grep -P ".+Sl.+/usr/local/MySource/endpoint" -c`
sleep 10
if [ $w -lt 2 ] 
then
echo 0 > /sys/class/leds/alix\:2/brightness
killall -9 /usr/local/MySource/endpoint
nohup /usr/local/MySource/endpoint &> /dev/null &
last_endpoint_m=`date`
echo $last_endpoint_m > /tmp/endpoint_msleep
echo $w >> /tmp/endpoint_msleep
else
echo 1 > /sys/class/leds/alix\:2/brightness
fi
sleep 10
done

If the process exists, the script will switch off a LED on my machine and start the process. The LED should be ON while the process is running.

I then run this script by adding the following line to /etc/rc.local:

nohup /usr/local/MyTools/additions/XR50_endpoint_m &> /dev/null &

When I run ps, I find that the XR50_endpoint_m & process is there.

My Machine is an ALIX board with limited resources (embedded) running Debian.

The question is:
The variable $w is always zero (I verified this from the output file /tmp/endpoint_msleep). Although the process exists and the script is working fine if I run it manually ($w=2)!

What do you think the reason is and what is the best way to monitor a process?

  • Did the answer work ? – Muhammad Gelbana Aug 27 '13 at 17:48
  • Log the output of ps u -A to a file to see exactly what's there. Are you sure the state is Al? You should use the -o option to ps instead of doing this dodgy filtering. – Gilles 'SO- stop being evil' Aug 27 '13 at 23:09
5

It is failing because you run ps u. From man ps:

u Display user-oriented format.

This means that ps will only list processes owned by the current user. When you run the script manually, that user is you so your process is listed correctly.

(As @Gilles very correctly pointed out, the use of -A will cause all processes to be printed so that explanation is just wrong. pgrep is still better though).


Anyway, a better way of doing this would be to use pgrep:

   pgrep,  pkill  - look up or signal processes based on
   name and other attributes

Change

w=`ps u -A | grep -P ".+Sl.+/usr/local/MySource/endpoint" -c` 

to

w=`pgrep -c endpoint`
|improve this answer|||||
  • u sets the display format, it doesn't affect the selection of processes. With -A, all processes are displayed. – Gilles 'SO- stop being evil' Aug 27 '13 at 23:08
  • " should be replaced by `. Thank you. – abahnihi Aug 29 '13 at 11:48
  • @user45980 so it should, thanks for pointing it out. However, (as usual) @Gilles is quite right and u with -A should print processes for all users. You should still use pgrep since that is what it is designed for but my original explanation for why it fails is wrong. – terdon Aug 29 '13 at 11:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.