《如何給腳本寫一個守護進程?》要點:
本文介紹了如何給腳本寫一個守護進程?,希望對您有用。如果有疑問,可以聯系我們。
在我們日常運維中,寫腳本監控一個進程是比較常見的操作,比如我要監控mysql進程是否消失,如果消失就重啟mysql,用下面這段代碼就可以實現:
#!/bin/sh
Date=` date ‘+%c’`
while :
do
if ! ps aux | grep -w mysqld | grep -v grep >/dev/null 2>&1
then
/etc/init.d/mysqld start
echo $Date mysqld was reboot >>/var/log/reboot_mysql.log
fi
done
但如果監控腳本本身出了問題,就無法按我們要求啟動程序了,這里這是以mysql為例子,但實際中如果是負責報警的腳本出了問題,報警沒發出來,那就比較尷尬了,所以為保證我們的檢查腳本能實時運行,我們有時需要寫一個守護進程(當然不止腳本,系統中的任何程序都可以靠守護進程啟動),這就是我們今天要說的主題,如何給腳本寫一個daemon進程,我們先上代碼:
#!/usr/bin/python
import subprocess
from daemon import runner
cmd = “/root/demo_script/restart_mysql.sh”
class App():
def __init__(self):
self.stdin_path = ‘/dev/null’
self.stdout_path = ‘/dev/tty’
self.stderr_path = ‘/dev/tty’
self.pidfile_path = ?‘/tmp/hello.pid’
self.pidfile_timeout = 5
def start_subprocess(self):
return subprocess.Popen(cmd, shell=True)
def run(self):
p = self.start_subprocess()
while True:
res = p.poll()
if res is not None:
p = self.start_subprocess()
if __name__ == ‘__main__’:
app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()
腳本比較簡單,沒什么特別的邏輯,關于daemon這個模塊如何使用,我這里給出一段官方的解釋,寫的非常明白,注意喲,是英文的,在這我就不翻譯了,如果不理解就查查字典,就當多學幾個單詞了吧.
__init__(self, app)
| ? ? ?Set up the parameters of a new runner.
|
| ? ? ?The `app` argument must have the following attributes:
|
| ? ? ?* `stdin_path`, `stdout_path`, `stderr_path`: Filesystem
| ? ? ? ?paths to open and replace the existing `sys.stdin`,
| ? ? ? ?`sys.stdout`, `sys.stderr`.
|
| ? ? ?* `pidfile_path`: Absolute filesystem path to a file that
| ? ? ? ?will be used as the PID file for the daemon. If
| ? ? ? ?“None“, no PID file will be used.
|
| ? ? ?* `pidfile_timeout`: Used as the default acquisition
| ? ? ? ?timeout value supplied to the runner’s PID lock file.
|
| ? ? ?* `run`: Callable that will be invoked when the daemon is
| ? ? ? ?started.
|
| ?do_action(self)
| ? ? ?Perform the requested action.
|
| ?parse_args(self, argv=None)
| ? ? ?Parse command-line arguments.
這樣就完成了,守護進程的啟動比較高大上,輸入以上代碼后,可以直接在終端輸入:
#python monitor.py? start
當然還有stop,restart等參數.
這里我介紹的是其中一個應用場景,實際中可以靈活運用,比如1臺服務器上啟動的程序過多,環境配置比較復雜,就可以先啟動daemon進程,然后通過daemon來啟動其它所有應用程序,就不用一個一個應用程序啟動了,而且還能起到實時監控的作用,很方便吧,這篇就到這里,有問題可以給我留言.
文章出處:python運維技術
轉載請注明本頁網址:
http://www.snjht.com/jiaocheng/4498.html