Bash:检查,如果未运行则运行进程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/13319716/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash: Check up, Run a process if not running
提问by Pawan
Bash: Check up, Run a process if not running
Bash:检查,如果未运行则运行进程
Hi , My requirement is that , if Memcache server is down for any reason in production , i want to restart it immediately
嗨,我的要求是,如果 Memcache 服务器在生产中因任何原因停机,我想立即重新启动它
Typically i will start Memcache server in this way with user as nobody with replication as shown below
通常我会以这种方式启动 Memcache 服务器,用户作为没有复制的用户,如下所示
memcached -u nobody -l 192.168.1.1 -m 2076 -x 192.168.1.2 -v
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 中添加了一个条目
(crontab -e)
(crontab -e)
*/5 * * * * /home/memcached/memcached_autostart.sh
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 ??
我的问题是在 memcached_autostart.sh 里面,为了自动重启 memcached 服务器,上面的脚本有什么问题吗??
Or
或者
If there is any better approach for achieving this (rather than using cron job )Please share your experience .
如果有任何更好的方法来实现这一点(而不是使用 cron 作业),请分享您的经验。
采纳答案by Saddam Abu Ghaida
Yes the problem is ps -eaf | grep 11211 | grep memcachedI assume is the process ID which always changes on every start, so what you should do is ps -ef | grep memcached
是的,问题是ps -eaf | grep 11211 | grep memcached我假设进程 ID 在每次启动时总是会改变,所以你应该做的是ps -ef | grep memcached
hope that helped
希望有所帮助
回答by Some programmer dude
Instead of running it from cronyou 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.
cron您可能想要创建一个适当的 init-script,而不是从它运行它。参见/etc/init.d/示例。此外,如果您这样做,大多数系统已经具有处理大部分工作的功能,例如检查启动、重新启动、停止、检查已经运行的进程等。
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.
大多数守护程序脚本将 pid 保存到一个特殊文件(例如/var/run/foo),然后您可以检查该文件是否存在。
For Ubuntu, you can see /etc/init.d/skeletonfor example script that you can copy.
对于 Ubuntu,您可以查看/etc/init.d/skeleton可以复制的示例脚本。

