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 .
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.
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.
You can list running processes using the ps command (ps means process status). The ps command displays your currently running processes in real-time.
Meaning. $! $! bash script parameter is used to reference the process ID of the most recently executed command in background.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With