将守护进程 class 扩展两个子 class 不起作用
Extending Daemon class by two subclasses does not work
这是我正在使用的守护进程class
它作为一个基础class,我想从另一个控制器文件中生成 2 个独立的守护进程
class Daemon:
"""A generic daemon class.
Usage: subclass the daemon class and override the run() method."""
def __init__(self, pidfile,outfile='/tmp/daemon_out',errfile='/tmp/daemon_log'):
self.pidfile = pidfile
self.outfile = outfile
self.errfile = errfile
def daemonize(self):
"""Deamonize class. UNIX double fork mechanism."""
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError as err:
sys.stderr.write('fork #1 failed: {0}\n'.format(err))
sys.exit(1)
# decouple from parent environment
os.chdir('/')
os.setsid()
os.umask(0)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError as err:
sys.stderr.write('fork #2 failed: {0}\n'.format(err))
sys.exit(1)
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = open(os.devnull, 'r')
so = open(self.outfile, 'a+')
se = open(self.errfile, 'a+')
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# write pidfile
atexit.register(self.delpid)
pid = str(os.getpid())
with open(self.pidfile,'w+') as f:
f.write(pid + '\n')
#method for removing the pidfile before stopping the program
#remove the commented part if you want to delete the output & error file before stopping the program
def delpid(self):
os.remove(self.pidfile)
#os.remove(self.outfile)
#os.remove(self.errfile)
def start(self):
"""Start the daemon."""
# Check for a pidfile to see if the daemon already runs
try:
with open(self.pidfile,'r') as pf:
pid = int(pf.read().strip())
except IOError:
pid = None
if pid:
message = "pidfile {0} already exist. " + \
"Daemon already running?\n"
sys.stderr.write(message.format(self.pidfile))
sys.exit(1)
# Start the daemon
self.daemonize()
self.run()
def stop(self):
#Stop the daemon.
# Get the pid from the pidfile
try:
with open(self.pidfile,'r') as pf:
pid = int(pf.read().strip())
except IOError:
pid = None
if not pid:
message = "pidfile {0} does not exist. " + \
"Daemon not running?\n"
sys.stderr.write(message.format(self.pidfile))
return # not an error in a restart
# Try killing the daemon process
try:
while 1:
os.kill(pid, signal.SIGTERM)
time.sleep(0.1)
except OSError as err:
e = str(err.args)
if e.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print (str(err.args))
sys.exit(1)
def restart(self):
"""Restart the daemon."""
self.stop()
self.start()
def run(self):
"""override this method when you subclass Daemon.
It will be called after the process has been daemonized by
start() or restart()."""
这是我在另一个文件中使用的代码
在这个文件中,我从单独的 classes 扩展守护进程 class 并覆盖 运行() 方法。
#! /usr/bin/python3.6
import sys, time, os, psutil, datetime
from daemon import Daemon
class net(Daemon):
def run(self):
while(True):
print("net daemon : ",os.getpid())
time.sleep(200)
class file(Daemon):
def run(self):
while(True):
print("file daemon : ",os.getpid())
time.sleep(200)
if __name__ == "__main__":
net_daemon = net(pidfile='/tmp/net_pidFile',outfile='/tmp/network_out.log',errfile='/tmp/net_error.log')
file_daemon = file(pidfile='/tmp/file_pidFile',outfile='/tmp/filesys_out.log',errfile='/tmp/file_error.log')
if len(sys.argv) == 2:
if 'start' == sys.argv[1]:
net_daemon.start()
file_daemon.start()
elif 'stop' == sys.argv[1]:
file_daemon.stop()
net_daemon.stop()
elif 'restart' == sys.argv[1]:
file_daemon.restart()
net_daemon.restart()
else:
print("Unknown command")
sys.exit(2)
sys.exit(0)
else:
print("usage: %s start|stop|restart" % sys.argv[0])
sys.exit(2)
第一个 class 到 运行 start() 方法目前 运行ning &
现在只有网络守护进程工作我如何让 2 classes 产生 2 个独立的守护进程??
真正的问题是您为所需的任务选择了错误的代码。你问的是 "How do I use this power saw to hammer in this nail?" 在这种情况下,它甚至不是带有说明手册的 professionally-produced 锯,而是你在某人的车库里发现的 home-made 锯,由一个可能知道的人制造他在做什么,但你不能真正确定,因为你不知道他在做什么。
您抱怨的最接近的问题在daemonize
:
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
第一次调用时,父进程退出。这意味着父进程永远无法启动第二个守护进程或执行任何其他操作。
对于可以由单独的程序管理的self-daemonizing程序,这正是您想要的。 (是否把所有的细节都弄对了,我不知道,但基本思路肯定是对的。)
对于产生守护进程的管理程序,这正是您不想要的。这就是你想要写的。所以这是错误的工具。
但是任务并没有太大的不同。如果您明白自己在做什么(并打开您的 Unix Network Programming
副本——没有人能很好地理解这些东西,以至于无法马上想到),您可以将一个转换为另一个。这可能是一个有用的练习,即使对于任何实际应用程序,我只使用 PyPI 上的 well-tested、well-documented、nicely-maintained 库之一。
如果您只是将父进程中发生的 sys.exit(0)
调用(而不是中间子进程中发生的调用!)替换为 return True
,会发生什么情况? (好吧,你可能还想用 return False
替换父级中的 sys.exit(1)
或引发某种异常。)然后 daemonize
不再守护你,而是生成一个守护进程并报告是否成功。哪个是你想要的,对吧?
不能保证其他所有事情都正确(我敢打赌它不会),但它确实解决了您询问的具体问题。
如果在那之后没有明显的错误,下一步可能是通读 PEP 3143(这很好地将史蒂文斯书中的所有细节翻译成 Python 术语并确保它们是 21 世纪 linux 和 BSD 的最新版本)并提出 运行 的测试清单,然后 运行 他们看看你有哪些不太明显的事情还是出错了。
这是我正在使用的守护进程class
它作为一个基础class,我想从另一个控制器文件中生成 2 个独立的守护进程
class Daemon:
"""A generic daemon class.
Usage: subclass the daemon class and override the run() method."""
def __init__(self, pidfile,outfile='/tmp/daemon_out',errfile='/tmp/daemon_log'):
self.pidfile = pidfile
self.outfile = outfile
self.errfile = errfile
def daemonize(self):
"""Deamonize class. UNIX double fork mechanism."""
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError as err:
sys.stderr.write('fork #1 failed: {0}\n'.format(err))
sys.exit(1)
# decouple from parent environment
os.chdir('/')
os.setsid()
os.umask(0)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError as err:
sys.stderr.write('fork #2 failed: {0}\n'.format(err))
sys.exit(1)
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = open(os.devnull, 'r')
so = open(self.outfile, 'a+')
se = open(self.errfile, 'a+')
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# write pidfile
atexit.register(self.delpid)
pid = str(os.getpid())
with open(self.pidfile,'w+') as f:
f.write(pid + '\n')
#method for removing the pidfile before stopping the program
#remove the commented part if you want to delete the output & error file before stopping the program
def delpid(self):
os.remove(self.pidfile)
#os.remove(self.outfile)
#os.remove(self.errfile)
def start(self):
"""Start the daemon."""
# Check for a pidfile to see if the daemon already runs
try:
with open(self.pidfile,'r') as pf:
pid = int(pf.read().strip())
except IOError:
pid = None
if pid:
message = "pidfile {0} already exist. " + \
"Daemon already running?\n"
sys.stderr.write(message.format(self.pidfile))
sys.exit(1)
# Start the daemon
self.daemonize()
self.run()
def stop(self):
#Stop the daemon.
# Get the pid from the pidfile
try:
with open(self.pidfile,'r') as pf:
pid = int(pf.read().strip())
except IOError:
pid = None
if not pid:
message = "pidfile {0} does not exist. " + \
"Daemon not running?\n"
sys.stderr.write(message.format(self.pidfile))
return # not an error in a restart
# Try killing the daemon process
try:
while 1:
os.kill(pid, signal.SIGTERM)
time.sleep(0.1)
except OSError as err:
e = str(err.args)
if e.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print (str(err.args))
sys.exit(1)
def restart(self):
"""Restart the daemon."""
self.stop()
self.start()
def run(self):
"""override this method when you subclass Daemon.
It will be called after the process has been daemonized by
start() or restart()."""
这是我在另一个文件中使用的代码
在这个文件中,我从单独的 classes 扩展守护进程 class 并覆盖 运行() 方法。
#! /usr/bin/python3.6
import sys, time, os, psutil, datetime
from daemon import Daemon
class net(Daemon):
def run(self):
while(True):
print("net daemon : ",os.getpid())
time.sleep(200)
class file(Daemon):
def run(self):
while(True):
print("file daemon : ",os.getpid())
time.sleep(200)
if __name__ == "__main__":
net_daemon = net(pidfile='/tmp/net_pidFile',outfile='/tmp/network_out.log',errfile='/tmp/net_error.log')
file_daemon = file(pidfile='/tmp/file_pidFile',outfile='/tmp/filesys_out.log',errfile='/tmp/file_error.log')
if len(sys.argv) == 2:
if 'start' == sys.argv[1]:
net_daemon.start()
file_daemon.start()
elif 'stop' == sys.argv[1]:
file_daemon.stop()
net_daemon.stop()
elif 'restart' == sys.argv[1]:
file_daemon.restart()
net_daemon.restart()
else:
print("Unknown command")
sys.exit(2)
sys.exit(0)
else:
print("usage: %s start|stop|restart" % sys.argv[0])
sys.exit(2)
第一个 class 到 运行 start() 方法目前 运行ning & 现在只有网络守护进程工作我如何让 2 classes 产生 2 个独立的守护进程??
真正的问题是您为所需的任务选择了错误的代码。你问的是 "How do I use this power saw to hammer in this nail?" 在这种情况下,它甚至不是带有说明手册的 professionally-produced 锯,而是你在某人的车库里发现的 home-made 锯,由一个可能知道的人制造他在做什么,但你不能真正确定,因为你不知道他在做什么。
您抱怨的最接近的问题在daemonize
:
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
第一次调用时,父进程退出。这意味着父进程永远无法启动第二个守护进程或执行任何其他操作。
对于可以由单独的程序管理的self-daemonizing程序,这正是您想要的。 (是否把所有的细节都弄对了,我不知道,但基本思路肯定是对的。)
对于产生守护进程的管理程序,这正是您不想要的。这就是你想要写的。所以这是错误的工具。
但是任务并没有太大的不同。如果您明白自己在做什么(并打开您的 Unix Network Programming
副本——没有人能很好地理解这些东西,以至于无法马上想到),您可以将一个转换为另一个。这可能是一个有用的练习,即使对于任何实际应用程序,我只使用 PyPI 上的 well-tested、well-documented、nicely-maintained 库之一。
如果您只是将父进程中发生的 sys.exit(0)
调用(而不是中间子进程中发生的调用!)替换为 return True
,会发生什么情况? (好吧,你可能还想用 return False
替换父级中的 sys.exit(1)
或引发某种异常。)然后 daemonize
不再守护你,而是生成一个守护进程并报告是否成功。哪个是你想要的,对吧?
不能保证其他所有事情都正确(我敢打赌它不会),但它确实解决了您询问的具体问题。
如果在那之后没有明显的错误,下一步可能是通读 PEP 3143(这很好地将史蒂文斯书中的所有细节翻译成 Python 术语并确保它们是 21 世纪 linux 和 BSD 的最新版本)并提出 运行 的测试清单,然后 运行 他们看看你有哪些不太明显的事情还是出错了。