最近想在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/shPATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin# m h dom mon dow user command17 * * * * root cd / && run-parts --report /etc/cron.hourly25 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/shps -fe|grep 'abc chanshu' |grep -v grepif [ $? -ne 0 ]then echo "abc chanshu start PRocess....." /disk1/d1/abc chanshu &else echo "/r/n 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 "/r/n abc chanshu already runing....." fi #10秒執行一次 sleep 10done &#####
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
新聞熱點
疑難解答