12

Bash: Check up, Run a process if not running

Hi , My requirement is that , if Memcache server is down for any reason in production , i want to restart it immediately

Typically i will start Memcache server in this way with user as nobody with replication as shown below

memcached -u nobody -l 192.168.1.1 -m 2076 -x 192.168.1.2 -v

So for this i added a entry in crontab this way

(crontab -e)

*/5 * * * * /home/memcached/memcached_autostart.sh

memcached_autostart.sh

#!/bin/bash
ps -eaf | grep 11211 | grep memcached
# if not found - equals to 1, start it
if [ $? -eq 1 ]
then
memcached -u nobody -l 192.168.1.1 -m 2076 -x 192.168.1.2 -v
else
echo "eq 0 - memcache running - do nothing"
fi

My question is inside memcached_autostart.sh , for autorestarting the memcached server , is there any problem with the above script ??

Or

If there is any better approach for achieving this (rather than using cron job ) Please share your experience .

Pawan
  • 31,545
  • 102
  • 256
  • 434

2 Answers2

7

Yes the problem is ps -eaf | grep 11211 | grep memcached I assume is the process ID which always changes on every start, so what you should do is ps -ef | grep memcached

hope that helped

maximus ツ
  • 7,949
  • 3
  • 25
  • 54
Saddam Abu Ghaida
  • 6,381
  • 2
  • 22
  • 29
  • 2
    won't that always return return 0 as it will always find the grep command? – BND Jun 29 '21 at 07:28
  • 2
    indeed the above command always finds the grep command. One can exlude grep process with: "ps -ef | grep memcache | grep -v grep". The latter command will return false if the process is not running, true if it is running – Mapad Sep 02 '21 at 14:04
  • 1
    Or use just pgrep. "pgrep -fl memcached" – tdmadeeasy Jul 23 '22 at 15:27
5

Instead of running it from cron you might want to create a proper init-script. See /etc/init.d/ for examples. Also, if you do this most systems already have functionality to handle most of the work, like checking for starting, restarting, stopping, checking for already running processes etc.

Most daemon scripts save the pid to a special file (e.g. /var/run/foo), and then you can check for the existence of that file.

For Ubuntu, you can see /etc/init.d/skeleton for example script that you can copy.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    I think there is also a function called `daemon` in `/etc/init.d/functions`. That also takes care of runfile.pid. So it is a good idea to source the functions file from your autostart script & call your program via daemon function. – anishsane Nov 10 '12 at 18:36