检查守护程序进程是否正在运行

时间:2015-10-19 13:06:31

标签: python django process daemon

我正在运行几个守护程序进程,我需要维护一个日志,以便在每隔15分钟的时间间隔后检查所有进程是否正在运行。我试图实现的代码是

def monitor_deamons():
   print "starting monitor"
   demo = ps -ef | grep -v grep | grep daemon #fails
   print demo
   PROCESSCOUNT=(ps -ef |grep -v grep |grep -cw <daemon name> #fails
   print PROCESSCOUNT

我通过以下命令启动所有这些deamon线程

python daemon_name.py start

2 个答案:

答案 0 :(得分:0)

我会发布一些成功执行你的第一个命令的代码,你存储在demo中的结果,你可以从中推断出如何获得PROCESS_COUNT

import subprocess

def monitor_deamons():
   print "starting monitor"

   ps = subprocess.Popen(('ps', '-ef'), stdout=subprocess.PIPE)
   grep = subprocess.Popen(('grep', '-v', 'grep'), stdin=ps.stdout, stdout=subprocess.PIPE)

   ps.stdout.close()  # Allow ps to receive a SIGPIPE if grep exits.

   grep_daemon = subprocess.Popen(('grep', 'daemon'), stdin=grep.stdout)

   grep.stdout.close() # Allow grep to receive a SIGPIPE if grep_daemon exits

   output = grep_daemon.communicate()[0]

   print output

monitor_deamons()

下次您遇到问题时,请解释您尝试过的内容并进行搜索。如果你研究过如何从Python执行进程你会找到子进程。从那里你可以用Google搜索如何在Python中的进程之间进行管道传输并获得与我类似的解决方案。

答案 1 :(得分:0)

您还可以使用python中提供的threading模块。如果在同一进程中运行以下命令,这将为您提供有关daemon_name.py进程创建的守护程序线程的更多信息。

获取主题计数:

In [12]: threading.activeCount()
Out[12]: 26

列出所有活动线程:

In [5]: threading.enumerate()
Out[5]: 
[<HistorySavingThread(IPythonHistorySavingThread, started 140361105082112)>,
 <Thread(Thread-17, started daemon 140359321511680)>,
 <Thread(Thread-9, started daemon 140359866775296)>,
 <Thread(Thread-22, started daemon 140359279548160)>,
 <Thread(Thread-5, started daemon 140360376239872)>,
 <Thread(Thread-18, started daemon 140359313118976)>,
 <Thread(Thread-10, started daemon 140359858382592)>,
 <Thread(Thread-20, started daemon 140359296333568)>,
 <Thread(Thread-21, started daemon 140359287940864)>,
 <Thread(Thread-13, started daemon 140359833204480)>,
 <Thread(Thread-16, started daemon 140359329904384)>,
 <_MainThread(MainThread, started 140361348196160)>,
 <Thread(Thread-19, started daemon 140359304726272)>]

访问任何线程并执行任何操作。

In [8]: t17 = threading.enumerate()[1]

In [9]: t17.
t17.daemon     t17.getName    t17.ident      t17.isAlive    t17.isDaemon   t17.is_alive   t17.join       t17.name       t17.run        t17.setDaemon  t17.setName    t17.start      

In [9]: t17.getName()
Out[9]: 'Thread-17'

我希望这会有所帮助。