linux 守护程序小记(指定进程不存在则启动 )

最近想在debian 下做个守护进程.用于守护指定的程序一直处于运行状态.网上查了下,有Crontab方式和写脚本执行方式.

  

Crontab

  Crontab 是系统自带的,类似于Windows的计划任务.相关介绍与使用可以查看:

  "

Debian的定时执行命令Crontab:http://www.tdblog.cn/?post=276

nano /etc/crontab #编辑配置后

root@:~# cat /etc/crontab 
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user  command
17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly
25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
#
#my server 3分钟执行一次
*/3 *  * * *   root    /bin/bash /abc/mysh/t2.sh

  t2.sh内容为:

查找程序名为"abc",程序参数为"chanshu" 的进程

不存在则启动.

注意: & 表示退出后,在后台继续执行.

#!/bin/sh
ps -fe|grep 'abc chanshu' |grep -v grep
if [ $? -ne 0 ]
then
    echo "abc chanshu start process....."
    /disk1/d1/abc chanshu &
else
    echo "
 abc chanshu  already runing....."
fi
#####

/etc/init.d/cron restart  #执行重启cron

  "

  不过Crontab可以指 月,日,小时,分以及一直运行,但却不能指定 间隔多少秒运行.这点就缺少点灵活性.

  可用Crontab来执行一些定时清理的任务,比如定期清理日志.

脚本实现

参考了

"

linux下用脚本实现:监控一个进程,不存在则将其启动。http://blog.csdn.net/rosekin/article/details/15341835

"

  参考这文章后,觉得这个方式更灵活.

  于是我的脚本

  t3.sh

 

#!/bin/sh

#一直执行
while [ 1 ]
    do

    ps -fe|grep 'abc chanshu' |grep -v grep
    if [ $? -ne 0 ]
    then
        #echo "abc chanshu start process....."
        /disk1/d1/abc chanshu  &
    #else
        #echo "
 abc chanshu  already runing....."
        
    fi

        #10秒执行一次
    sleep 10
done &
#####

  

  t3.sh 是一直在后台执行,每10秒执行一次扫描任务. 为什么 扫描了程序,还要扫描程序的参数? 不同的参数可以让相同的程序 执行不同的分工.

  把t3.sh放入开机启动项,就ok了.

  

debian设置开机自启动

这个的方法很多,个人觉得编辑/etc/rc.local配置最简单有效。

保存文件,重启系统即可生效.

#代码如下    
sudo vi /etc/rc.local

#在exit 0之前添加软件启动命令。如:

/disk1/aaa/t3.sh

至此一个简单的设置守护进程的方法就完成了.

 

如果想要中止进程可以用 pkill -9 进程名或进程部分名.

参见:http://blog.sina.com.cn/s/blog_975a2a540100ywyx.html

原文地址:https://www.cnblogs.com/bleachli/p/4683617.html