newlisp 监控Linux进程 一

来源:互联网 发布:java定义整形数组 编辑:程序博客网 时间:2024/06/11 06:33

之前我的newlisp 监控redmine中描述了监控redmine进程的方法,今天更进一步,添加一个配置文件,里面描述了要监控的进程list,这样每次逐个检查本机的进程.

先来实现个简单的检查,一个函数check-proces,接受一个字符串,用来检查进程是否存在

#!/usr/bin/newlisp(define (check-process filter-str)  (set 'r (exec (append "ps -def | grep " filter-str)))  (set 'l (length r))  (> l 3))(if (check-process "dispatch")    (println "redmine is alive")  (println "redmine is dead"))(exit)

好,添加一个配置文件叫做filter.lsp, 下面的filters是一个list,里面每个元素也是一个list,并且分两部分,一是用来检查进程的字符串,二是要检查进程的有意义的名称,可以用于写日志。

(set 'filters (list '("dispatch" "redmine")))    

然后之前的process.lsp内容修改为:

#!/usr/bin/newlisp(load "/opt/detector/filter.lsp")(define (check-process filter-str)  (set 'r (exec (append "ps -def | grep " filter-str)))  (set 'l (length r))  (= 3 l))(dolist (sub-list filters)  (if (check-process (first sub-list))      (println (append (sub-list 1) " is alive"))    (println (append (sub-list 1) " is dead"))))(exit)

ok, 再进一步,写日志, 添加了add-log函数

#!/usr/bin/newlisp(set 'cur-path "/opt/detector")(load (append cur-path "/filter.lsp"))(define (check-process filter-str)  (set 'r (exec (append "ps -def | grep " filter-str)))  (set 'l (length r))  (= 3 l))(define (add-log msg)  (println msg)  (append-file (append cur-path "/process.log") (append "\n" (string (now 480)) " "))  (append-file (append cur-path "/process.log") (append  ": " msg))  )(dolist (sub-list filters)  (if (check-process (first sub-list))      (add-log (append (sub-list 1) " is alive\n"))    (add-log (append (sub-list 1) " is dead\n"))))(exit)