Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Check up, Run a process if not running [duplicate]

Tags:

bash

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 .

like image 962
Pawan Avatar asked Nov 10 '12 05:11

Pawan


People also ask

How do I check if a process is running in bash?

Bash commands to check running process: pgrep command – Looks through the currently running bash processes on Linux and lists the process IDs (PID) on screen. pidof command – Find the process ID of a running program on Linux or Unix-like system.

How do you check if a PID is running or not?

The easiest way to find out if process is running is run ps aux command and grep process name. If you got output along with process name/pid, your process is running.

How do you check if a process is running or not in Linux?

You can list running processes using the ps command (ps means process status). The ps command displays your currently running processes in real-time.

What does $! Mean in Linux?

Meaning. $! $! bash script parameter is used to reference the process ID of the most recently executed command in background.


2 Answers

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

like image 91
2 revs, 2 users 89% Avatar answered Sep 19 '22 14:09

2 revs, 2 users 89%


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.

like image 26
Some programmer dude Avatar answered Sep 18 '22 14:09

Some programmer dude